發表文章

目前顯示的是 2020的文章

Sorting - Bubble Sort [Easy]

 https://ithelp.ithome.com.tw/articles/10226353 Sample Input 0 STDIN Function ----- -------- 3 a[] size n = 3 1 2 3 a = [1, 2, 3] Sample Output 0 Array is sorted in 0 swaps. First Element: 1 Last Element: 3 Explanation 0 The array is already sorted, so   swaps take place. Sample Input 1 3 3 2 1 Sample Output 1 Array is sorted in 3 swaps. First Element: 1 Last Element: 3 Explanation 1 The array is  not sorted , and its initial values are:  . The following   swaps take place: At this point the array is sorted and the three lines of output are printed to stdout. static   void  countSwaps( int [] a) {        int  temp;          int  totalswap= 0 ;          for ( int  i= 0 ;i<a.length;i++)         {             ...

Arrays - 2D Array -DS [Easy]

 https://ithelp.ithome.com.tw/articles/10199983 要計算出所謂的 hourglass (沙漏) 的總和 目的 那我們就是要寫一個方法, 來找出最大 hourglass 輸入限制 input 會是個 6*6 的二維陣列 陣列中每個元素的值介於 9 ~ -9 解題概念: 由此題我們可以觀察到 hourglass (沙漏)的圖形 a b c d e f g 其實是... top : 3 個元素 a b c middle : 中間一個元素 d buttom : 3 個元素 e f g 所以其實我們只要這樣把 a ~ g 都加起來就對了 也就是如下 假定陣列是 arr[6][6] 6*6的二維陣列 那我們要算的其實就是 arr[i][j] arr[i][j+ 1 ] arr[i][j+ 2 ] arr[i+ 1 ][j+ 1 ] arr[i+ 2 ][j] arr[i+ 2 ][j+ 1 ] arr[i+ 2 ][j+ 2 ] 這樣的 hourglass sum (沙漏和) 另外 由於 a b c d e f g 在這樣的圖形中, 其實只有 7 個值, 陣列中每個元素的值介於 9 ~ -9 所以我們可以知道 最小的 hourglass sum 會是 7 * -9 = -63 所以可以把 -63 當作一個初始的基準值 只要算出的 hourglass sum 比之前算出的大, 我們就以這個最大的 hourglass sum 為答案 程式碼 package hourglass; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Solution { // Complete the hourglassSum function below. static int hourglassSum ( int [][] arr) { int max = 7 * - 9 ; for ( int i = 0 ; i < 6 ; i...