劍指offer面試題4--在二維數組中搜索整數

Java 

Method 1: search from the upper right corner,you can search from the lower left corner also.

package offer;

public class num4_searchInMatrix {
	/*
	 * description:
	 * in a two-dimensional array,each row is sorted in ascending from left to right;
	 * each column is sorted in ascending from top to bottom
	 * please complete a function, enter such a array and an inter;
	 * and judge whether the array contains the integet
	 
	 */
	public static int[] searchMatrix(int[][] arr,int target,int rows,int cols)
	{
		int[] index={0,-1,-1};//flag,row,col
		if(arr==null||rows<=0||cols<=0)
		{
			index[0]=0;
		}
		int row=0,col=cols-1;
		while(row<rows&&col>0)
		{
			if(arr[row][col]==target)
			{
				index[0]=1;
				index[1]=row;
				index[2]=col;
				break;
			}
			else if(arr[row][col]>target)
			{
				col--;
			}else
			{
				row++;
			}
		}
		
		return index;
	}
	

}

 

 

python

import numpy as np
def search(arr, target):
    flag = 0
    arr = np.array(numbers)
    row = 0
    if arr == [] or arr.shape[0]<=0 or arr.shape[1]<=0:
         return 0,-1,-1
    col = arr.shape[1]-1
    while row<arr.shape[0] and col>0:
        if arr[row][col] == target:
            flag=1
            break
        elif arr[row][col]>target:
            col=col-1
        else:
            row = row+1
    return flag,row,col



if __name__ == '__main__':
    numbers = []
    ans = search(numbers,20)
    if ans[0]==1:
        print(ans[1],ans[2])
    else:
        print("not found")

        

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章