1. 程式人生 > >劍指offer二維陣列中的查詢

劍指offer二維陣列中的查詢

從第一行最右邊開始找,如果想要更大的數,往下找;想要更小的數,往左;如果超出範圍,說明沒有;

public class Solution {
    public boolean Find(int target, int [][] array) {
        int rows = array.length;
        int cols = array[0].length;
        int i = rows - 1;
        int j = 0;
        while(i>= 0 && j < cols){
            if(array[i][j]< target){
                j ++;
            }
            else if(array[i][j]> target){
                i--;
            }
            else{return true;}
        }return false;
    }
}

python 

# -*- coding:utf-8 -*-
class Solution:
    # array 二維列表
    def Find(self, target, array):
        # write code here
        rows = len(array)
        cols = len(array[0])
        i = rows - 1
        j = 0
        while((i>=0)&(j<cols)):
            if(array[i][j])>target:
                i -= 1
            elif(array[i][j]<target):
                j += 1
            else:
                return True
        return False