leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/
Count Negative Numbers in a Sorted Matrix - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
완전 탐색으로 풀면 더 쉽게 풀겠지만, 문제 분류가 이진 탐색이기 때문에 이진 탐색 방식으로 풀었다.
각각의 1차원 배열에 음수의 총 갯수를 구하는 문제이다!
public int countNegatives(int[][] grid) {
int count = 0;
for (int[] arr : grid) {
int idx = negativeNumIdx(arr);
count += (arr.length - idx);
}
return count;
}
private int negativeNumIdx(int[] arr) {
int high = arr.length - 1;
int low = 0;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] < 0) {
while (mid != -1 && arr[mid] < 0) {
mid--;
}
return mid + 1;
}
low = mid + 1;
}
return arr.length;
}
1차원 배열 요소들은 내림차순 되어있다.
반복문을 통해 배열의 맨 앞에 있는 음수의 idx를 구해서, 배열의 길이만큼 빼면 요소 당 음수의 갯수를 구할 수 있다.
'코딩테스트' 카테고리의 다른 글
해커랭크 - Inserting a Node Into a Sorted Doubly Linked List (0) | 2021.04.25 |
---|---|
프로그래머스 - 게임 맵 최단거리 (0) | 2020.10.17 |
leetcode - Shortest Unsorted Continuous Subarray (0) | 2020.09.28 |
프로그래머스 - 가장 큰 수 (0) | 2020.09.13 |
프로그래머스 - 기지국 설치 (0) | 2020.09.07 |