国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > php教程 > 搜索二维矩阵II

搜索二维矩阵II

来源:程序员人生   发布时间:2016-08-09 08:16:43 阅读次数:2064次

题目

写出1个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。

这个矩阵具有以下特性:

每行中的整数从左到右是排序的。
每列的整数从上到下是排序的。
在每行或每列中没有重复的整数。

解题

和判断1个数是不是在这样的2维矩阵中1样,判断找到合适就结束了
这个题目有多个,找到1个的时候还要继续找,直到找完

public class Solution { /** * @param matrix: A list of lists of integers * @param: A number you want to search in the matrix * @return: An integer indicate the occurrence of target in the given matrix */ public int searchMatrix(int[][] matrix, int target) { // write your code here if(matrix == null) return 0; int row = matrix.length; if(row ==0) return 0; int col = matrix[0].length; int count =0; int i=0; int j=col-1; // 右上开始 while(i<row && j>=0){ if(matrix[i][j] > target){ // 大 列 ⑴ j--; }else if(matrix[i][j]< target){ // 小 行+1 i++; }else{ // 行+1 列⑴,题目说明每行或每列没有重复数 count++; i++; j--; } } return count; } }

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生