Search 2D matrix II
来源:互联网 发布:java 执行顺序 编辑:程序博客网 时间:2024/06/05 16:49
Search 2D matrix II
在矩阵中搜索目标数字的出现次数。
Write an efficient algorithm that searches for a value in an m x n matrix, return the occurrence of it.
This matrix has the following properties:
* Integers in each row are sorted from left to right.
* Integers in each column are sorted from up to bottom.
* No duplicate integers in each row or column. 无重复数字
ExampleConsider the following matrix:
[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]
Given target = 3, return 2.
public int searchMatrix(int[][] matrix, int target) { if(matrix == null || matrix.length == 0) { return 0; } int row = matrix.length - 1; int col = matrix[0].length - 1; int count = 0; for(int i = 0; i <= row; i++) { if(target >= matrix[i][0] && target <= matrix[i][col]) { count += bs(matrix[i], target); } } return count;}private int bs(int[] nums, int target) { int start = 0; int end = nums.length - 1; int mid; while(start + 1 < end) { mid = start + ((end - start) >> 1); if(target < nums[mid]) { end = mid; } else if(target > nums[mid]) { start = mid; } else { return 1; } } if(target == nums[start]) { return 1; } else if(target == nums[end]) { return 1; } else { return 0; }}
一次遍历:
public int searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0) { return 0; } if (matrix[0] == null || matrix[0].length == 0) { return 0; } int row = matrix.length - 1; int col = 0; int size = matrix[0].length - 1; int count = 0; while (row >= 0 && col <= size) { if (matrix[row][col] == target) { count++; row--; } else if (matrix[row][col] < target) { col++; } else if (matrix[row][col] > target) { row--; } } return count; }
思路:
1. 搜索:对每一行进行bs,统计所有行 O(mlog(n))。每行没有重复,每行最后一个是最大值。 如果target比它大,则该行可略过。
2. 一次遍历。从左下角开始向右上前进,每行没有重复。同一列中,上一行比本行小。
0 0
- Search 2D matrix II
- Search a 2D Matrix II
- Lintcode - Search in 2D matrix II
- [刷题]Search a 2D Matrix II
- lintcode:Search a 2D Matrix II
- #leetcode#Search a 2D Matrix II
- Search a 2D Matrix II
- [LeetCode] Search a 2D Matrix II
- leetcode: Search a 2D Matrix II
- leetcode - Search a 2D Matrix II
- Search a 2D Matrix II
- 240Search a 2D Matrix II
- [leetcode] Search a 2D Matrix II
- 【leetcode】Search a 2D Matrix II
- Search a 2D Matrix II
- Search a 2D Matrix II
- Search a 2D Matrix II
- Leetcode: Search a 2D Matrix II
- ::after和::before
- 第二章 7——10题
- 第三周 项目一(3):三角形类的构造函数(有默认参数的构造函数)
- Json转换利器Gson——简单对象转化和带泛型的List转化
- Fragment详解
- Search 2D matrix II
- hdu 1222 Wolf and Rabbit(递归)
- 用composer进行更新操作
- JavaScript随机产生文字实例
- How-to Dump Keys from Memcache
- 服务器安全部署文档
- C/C++中函数参数传递详解
- leetcode--Unique Binary Search Trees
- Employees Earning More Than Their Managers