題目: 在一個(gè)二維數(shù)組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請(qǐng)完成一個(gè)函數(shù),輸入這樣的一個(gè)二維數(shù)組和一個(gè)整數(shù),判斷數(shù)組中是否含有該整數(shù)
思路: 矩陣是有序的,從左下角來看,向上數(shù)字遞減,向右數(shù)字遞增, 因此從左下角開始查找,當(dāng)要查找數(shù)字比左下角數(shù)字大時(shí)。右移 要查找數(shù)字比左下角數(shù)字小時(shí),上移
代碼
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; }}/*** 數(shù)組中存在輸出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.新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注