二維陣列中的查詢 offer
阿新 • • 發佈:2018-11-03
java中使用length獲取二維陣列的長度
public class ArrayList{
public static void main(String[] args) {
int[][] arr = new int [3][3];//定義一個二維陣列
int sum =0;//記錄長度
for(int a = 0 ;a<arr.length;a++){//獲取行的長度
for(int b = 0 ;b<arr[a].length;b++){//獲取列的長度
sum++;//長度+1
}
}
System.out.println(sum);//輸出長度
}
}
程式碼實現
import java.util.Scanner; public class HelloWorld { public static boolean Find(int target, int[][] array) { int row = 0; int col = array[0].length - 1; while (row < array.length - 1 & col >= 0) { if (array[row][col] == target) return true; else if (array[row][col] > target) col--; else row++; } return false; } public static void main(String[] args) { int[][] testArray = new int[5][5]; int temp = 1; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { testArray[i][j] = temp; temp++; } } System.out.print("輸入要查詢的數字"); Scanner input = new Scanner(System.in); int number = input.nextInt(); if (Find(number, testArray) == true) System.out.print("陣列中包含" + number); else System.out.print("陣列中不包含" + number); } }
結果檢視