LeetCode(1351) - Count Negative Numbers in a Sorted Matrix

IT/알고리즘 2020.02.25 댓글 Hyunyoung Kim

 

값이 증가하지 않지 상태로 정렬된 m*n 크기의 이차원 배열이 주어졌을 때

음수의 개수를 찾아라

 

 

Phyton

class Solution:
    def countNegatives(self, grid: List[List[int]]) -> int:
        result=0
        for i in grid:
            for j in range(len(i)-1,-1,-1):
                if i[j]<0:
                    result+=1
                if i[j]>=0:
                    break
        return result

 

Javascript

 

var countNegatives = function(grid) {
    let result=0;
    for(let i of grid){
        for(let j=i.length-1; j>=0; j--){
            if(i[j]<0) result++;
            if(i[j]>=0) break;
        }
    }
    return result
};

 

이 문제는.. Binary Search를 이용하는게 가장 효율이 좋다!

댓글