發表文章

目前顯示的是有「Arrays」標籤的文章

Arrays - Minimum Swaps 2 [M]

 Sample Input 0 4 4 3 1 2 Sample Output 0 3 Explanation 0 Given array  After swapping   we get  After swapping   we get  After swapping   we get  So, we need a minimum of   swaps to sort the array in ascending order. static   int  minimumSwaps( int [] arr) {        int  arrLen = arr.length;          int  count =  0 ;          int  [] sarr = arr.clone();         Arrays.sort(sarr);                   for  ( int  i =  0 ; i < arrLen; i++) {              if  (arr[i] != sarr[i]) {     ...

Arrays - Left Rotation [Easy]

  A   left rotation   operation on an array shifts each of the array's elements     unit to the left. For example, if     left rotations are performed on array   , then the array would become   . Note that the lowest index item moves to the highest index in a rotation. This is called a   circular array . Given an array   of   integers and a number,  , perform   left rotations on the array. Return the updated array to be printed as a single line of space-separated integers. Sample Input 5 4 1 2 3 4 5 Sample Output 5 1 2 3 4   static   int [] rotLeft( int [] a,  int  d) {   int [] arr =  new   int [a.length];          int  N = a.length;          for  ( int  i =  0  ; i < N;  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...