1. 程式人生 > >二維陣列中的查詢(行遞增矩陣的查詢)

二維陣列中的查詢(行遞增矩陣的查詢)

僅作為個人筆記

在一個二維陣列中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函式,輸入這樣的一個二維陣列和一個整數,判斷陣列中是否含有該整數。

C++

class Solution {
public:
    bool Find(vector<vector<int> > array,int target) {
        int rowCount = array.size();
        int colCount = array[0].size();
        int i, j;
        for
(i = rowCount-1,j = 0; i >= 0 && j < colCount;) { if(target == array[i][j]) return true; else if(target < array[i][j]) { i--; continue; } else { j++; continue
; } } return false; } };

Java

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

Python

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

定位法:先定位到左下角。用左下角元素跟查詢元素比較,如果要查詢元素小於左下角元素,上移一行,如果大於左下角元素,右移一列。上述方法的時間複雜度為O(m+n)。