(二维数组中查找target)LeetCode#74. Search a 2D Matrix #240. Search a 2D Matrix II
2017-06-09 08:01
330 查看
题目:给定一个二维数组matrix和一个target,二维数组的每行的元素都是从左到右递增,每一行的第一个元素都大于上一行的最后一个元素。如下所示
难度:Medium
思路:根据数组元素的大小规律,可以从第0行第n列(n=matrix[0].lenght-1)开始搜索,然后不断更新i和j
代码:
Search a 2D Matrix II
数组的特点:每行从左到右递增,每列从上到下递增
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
难度:Medium
思路:根据数组元素的大小规律,可以从第0行第n列(n=matrix[0].lenght-1)开始搜索,然后不断更新i和j
代码:
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix == null || matrix.length == 0 || matrix[0].length == 0){ return false; } int rows = matrix.length; int cols = matrix[0].length; int i = 0; int j = cols-1; while(i < rows && j >= 0){ if(matrix[i][j] == target){ return true; }else if(matrix[i][j] > target){ j--; }else{ i++; } } return false; } }
Search a 2D Matrix II
数组的特点:每行从左到右递增,每列从上到下递增
相关文章推荐
- [算法][LeetCode]Search a 2D Matrix——二维数组的二分查找
- Search a 2D Matrix(在二维数组中查找)
- 【LeetCode】Search a 2D Matrix && 【九度】题目1384:二维数组中的查找
- Search a 2D Matrix:二分查找二维数组
- 74. Search a 2D Matrix&240. Search a 2D Matrix II
- Leetcode 240 Search a 2D Matrix II (二分法和分治法解决有序二维数组查找)
- leetcode题解-74. Search a 2D Matrix && 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II(二分查找)
- Leetcode 240 Search a 2D Matrix II (二分法和分治法解决有序二维数组查找)
- 剑指offer 面试题3:二维数组(矩阵)中数的查找(leetcode 74. Search a 2D Matrix) 题解
- Leetcode刷题记—— Search a 2D Matrix(在二维数组里查找)
- Leetcode 74. Search a 2D Matrix & 240. Search a 2D Matrix II
- LeetCode - 74. Search a 2D Matrix & 240. Search a 2D Matrix II
- 74.Search a 2D Matrix&240. Search a 2D Matrix II
- 字符串算法——查找二维数组中元素(Search a 2D Matrix II)
- LeetCode OJ:Search a 2D Matrix(二维数组查找)
- 二维数组中的查找(LeetCode: 74. Search a 2D Matrix)
- [算法][LeetCode]Search a 2D Matrix——二维数组的二分查找
- [Divide and Conquer]240. Search a 2D Matrix II
- 240. Search a 2D Matrix II(unsolved)