[Offer] [face to prove safety questions 3: Look for two-dimensional array]

"Prove safety Offer" List


One, Title Description

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

Second, problem-solving ideas

If that description, each column are ordered from top to bottom in increasing order, each row sorted increasing order from left to right. Both each row and each column is sorted. For elements in the array sorted, with the dichotomy is undoubtedly a better algorithm. I was the first to find each line, if the first element of this line element is greater than the element you want to find, there is no need to find elements of this line. If less than it would use a binary search that element.

Third, Code Description

package com.acm.Secondmonth;

public class Test03 {
	
	/**
	 * 二分查找 
	 * 首先从列开始  只要比该列的第一个元素大,就表示可以搜索这一行
	 * 
	 * @param matrix
	 * @param i
	 * @return
	 */
	private static boolean find(int[][] matrix, int k) {
		if(matrix == null) {
			throw new RuntimeException("invaild input! the array is null!");
		}
		for(int i=0 ; i<matrix.length ; i++) {
			if(matrix[i][0] < k) {
				if(binarySearch(matrix[i] , k)) {
					return true;
				}
			}else if(matrix[i][0] == k) {
				return true;
			}
		}
		
		return false;
	}

	public static boolean binarySearch(int[] num , int k) {
		
		int start =0 , end = num.length-1;
		while(start <= end) {
			int mid = (end+start)/2;
			if(num[mid] > k) {
				end = mid-1;
			}else if(num[mid] < k) {
				start = mid+1;
			}else {
				return true;
			}
		}
		return false;
	}
	public static void main(String[] args) {
        int[][] matrix = {
                {1, 2, 8, 9},
                {2, 4, 9, 12},
                {4, 7, 10, 13},
                {6, 8, 11, 15}
        };
        System.out.println(find(matrix, 7));    // 要查找的数在数组中
        System.out.println(find(matrix, 5));    // 要查找的数不在数组中
        System.out.println(find(matrix, 1));    // 要查找的数是数组中最小的数字
        System.out.println(find(matrix, 15));   // 要查找的数是数组中最大的数字
        System.out.println(find(matrix, 0));    // 要查找的数比数组中最小的数字还小
        System.out.println(find(matrix, 16));   // 要查找的数比数组中最大的数字还大
        System.out.println(find(null, 16));     // 健壮性测试,输入空指针
    }


}

 

Published 14 original articles · won praise 1 · views 5524

Guess you like

Origin blog.csdn.net/Vpn_zc/article/details/84295613