Question Link:

https://leetcode.com/problems/search-a-2d-matrix/

Question Description

Given a sorted matrix, find an element
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 Output: true
image.png

Simulation

Solution 1: Array Traverse

Search start from top right corner (Start). If value larger than current, curY++, else curX—

matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Leetcode 74 Search a 2D Matrix - 图2

matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Leetcode 74 Search a 2D Matrix - 图3

Implementation

Solution 1:

  1. public boolean searchMatrix(int[][] matrix, int target) {
  2. int curX = matrix[0].length - 1;
  3. int curY = 0;
  4. while (curX >= 0 && curY < matrix.length) {
  5. if (matrix[curY][curX] == target) {
  6. return true;
  7. } else if (matrix[curY][curX] > target) {
  8. curX--;
  9. } else {
  10. curY++;
  11. }
  12. }
  13. return false;
  14. }