行列均递增的二维数组中查找元素

来源:互联网 发布:qq文件夹删除数据恢复 编辑:程序博客网 时间:2024/05/18 22:11

剑指offer中的一个原题:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序,

输入一个二维数组和一个数,判断该数组中是否有该数。

解决思路:每次从二维数组的右上角作为查找起始点,如果右上角元素大于目标值,则把查找点所在的列排除,如果右上角元素

小于目标值则把查找点所在的行排除,如果右上角元素等于目标值则返回true;在新的查找区域中将右上角元素再作为查找点继续循环

以上操作。

优化思路:例如一下二维数组:

1    3 5 7 9 10 11 14 
12 14 16 18 19 20 22 24

在其中查找元素16,则按照上述的解决思路在查找区域将会变成一个一维数组12 14 16 18 19 20 22 24,从而在该一维数组中遍历

查找元素16,效率依然会很低,所以优化思路是:如果查找区域最后变成一个一维数组时(可能是二维数组中的最后一行或者是第一列),

应该此时采样折半查找。

import java.util.Scanner;public class Main{public static void main(String args[]){Scanner sc = new Scanner(System.in);int m = sc.nextInt();//行数int n = sc.nextInt();//列数int arr[][] = new int[m][n];for(int i = 0;i<m;i++){for(int j = 0;j<n;j++){arr[i][j] = sc.nextInt();}}int targetValue = sc.nextInt();System.out.println(MulArrayFind(arr,targetValue));}//方法public static boolean MulArrayFind(int[][] arr,int targetValue){//右上角的坐标int topRightCornerX = 0;int topRightCornerY = arr[0].length-1;while( topRightCornerX < arr.length && topRightCornerY >=0){if(arr[topRightCornerX][topRightCornerY]==targetValue){System.out.println("OK1");return true;}if(arr[topRightCornerX][topRightCornerY]>targetValue){topRightCornerY--;}else{topRightCornerX++;}//优化对于最后在单行或者单列中进行搜索时,采用二分查找进行搜索if(topRightCornerX==arr.length-1 ){//最后一行进行二分查找int begin = 0,end = topRightCornerY;while(begin<=end){int mid = (begin+end)/2;if(arr[topRightCornerX][mid] == targetValue){System.out.println("OK2");return true;}if(arr[topRightCornerX][mid] < targetValue){begin = mid+1;}else{end = mid-1;}}return false;}if(topRightCornerY==0){//第一列进行二分查找int begin = topRightCornerX,end = arr.length-1;while(begin <= end){int mid = (begin+end)/2;if(arr[mid][0] == targetValue){System.out.println("OK3");return true;}if(arr[mid][0] < targetValue){begin = mid+1;}else{end = mid-1;}}return false;}}return false;}}



原创粉丝点击