240. Search a 2D Matrix II

JJ·2021년 1월 8일
0

Algorithms

목록 보기
55/114
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int[] first = matrix[0];
        int height = matrix.length - 1;
        int[] last = matrix[height];
        
        int x0 = 0;
        int xl = 0;
        
        for (int i = 0; i < first.length; i++) {
            if (first[i] <= target) {
                x0 = i;
            }
        }
        
        for (int j = 0; j <= height; j++) {
            if (matrix[j][x0] == target) return true;
        }
        
        return false;
    }
}

난독이 왔읍니다..

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int h = matrix.length;
        int w = matrix[0].length;
        
        int x0 = 0;
        int y0 = h - 1;
        
        while (y0 >= 0 && x0 < w) {
            if (matrix[y0][x0] > target) {
                y0--;
            } else if (matrix[y0][x0] < target) {
                x0++;
            } else {
                return true; 
            }
        }
        
        return false; 
    }
}

Runtime: 6 ms, faster than 33.00% of Java online submissions for Search a 2D Matrix II.
Memory Usage: 44.1 MB, less than 97.06% of Java online submissions for Search a 2D Matrix II.

머리 잘 썼다고 생각했는데 상당히 느린..

0개의 댓글