Algorithms question 1: Find the number of two-dimensional array

1. Topic

(The length of each one-dimensional array of same), each row from left to right in order of ascending sort, to sort each column in a two-dimensional array in order of increasing from top to bottom. A complete function, enter such a two-dimensional array and an integer, it is determined whether the array contains the integer.

2. Answers

	/*
	 * 思路1:遍历每一行,二分查找是否属于这一行
	 */
	public static boolean find01(int[][] arr, int target) {
		// 不在数组范围内直接返回false
		if(target<arr[0][0] || target>arr[arr.length-1][arr[0].length-1])
			return false;
		
		for(int i=0; i<arr.length; i++) {
			// 不在此行范围内继续下一行
			if(target<arr[i][0]||target>arr[i][arr[i].length-1])
				continue;
			
			int left = 0;
			int right = arr[i].length-1;
			int mid = (arr[i].length)/2 ;
			while(left <= right) {
				if(target==arr[i][mid])
					return true;
				if(target>arr[i][mid]) {
					left = mid + 1;
				} else {
					right = mid - 1;					
				}
				mid = (left + right)/2;
			}
		}
		return false;
	}
	/*
	 * 思路2:以对角线上的元素为原点将二维数组分成4个象限,从左上角向右下角移动原点,
	 * 若target在某两个原点之间,则可以去掉二四象限,从一三象限中寻找
	 * 也可不用从左上角向右下角移动原点,采用二分查找的思想,从中间开始
	 * 实现起来比较麻烦:弃
	 */
	/*
	 * 思路3:从右上角或者从左下角开始查找
	 * 以左下角为例:左下角元素是一列中的最大的元素,一行中最小的元素,当target<这个数则上移一行,否则右移一行
	 */
	public static boolean find03(int[][] arr, int target) {
		// 不在数组范围内直接返回false
		if(target<arr[0][0] || target>arr[arr.length-1][arr[0].length-1])
			return false;	
		
		int index1 = arr.length-1;
		int index2 = 0;
		while(index1>=0&&index2<arr[0].length) {
			int point = arr[index1][index2];
			if(target == point)
				return true;
			
			if(target>point) {
				index2++;				
			} else {
				index1--;
			}
		}		
		return false;
	}

Welcome to correct me, if any better ideas, welcome to discuss ~~

Released eight original articles · won praise 0 · Views 117

Guess you like

Origin blog.csdn.net/qq_42994084/article/details/102639099