題目: 在一個二維數組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數
思路: 矩陣是有序的,從左下角來看,向上數字遞減,向右數字遞增, 因此從左下角開始查找,當要查找數字比左下角數字大時。右移 要查找數字比左下角數字小時,上移
代碼
package javaTest;class Solution { public boolean Find(int target, int [][] array) { int rowLength = array.length; int colLength = array[0].length; int row = rowLength-1; int col = 0; boolean flag = false; while(true) { if(row < 0 || col >= colLength ) break; if(array[row][col] == target){ flag = true; break; } if(array[row][col] > target) row--; else if(array[row][col] < target) col++; } if(flag){ return true; } return false; }}/*** 數組中存在輸出Yes* 否則輸出No*/public class Main { /** * @param args */ public static void main(String[] args) { int [][] array = {{1, 5, 7, 10, 15},{3 , 6, 9, 12, 18},{5, 7, 10, 14, 20},{7, 10, 15, 17, 23 }}; Solution objSolution = new Solution(); boolean res = objSolution.Find(25, array); if(res) System.out.
|
新聞熱點
疑難解答