Leetcode - 1365. How Many Numbers Are Smaller Than the Current Number

숲사람·2022년 12월 12일
0

멘타트 훈련

목록 보기
195/237

문제

배열 요소값 보다 작은 값을 가진 요소의 갯수를 구하라.

Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation: 
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). 
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1). 
For nums[3]=2 there exist one smaller number than it (1). 
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).

해결 아이디어

  • brute force 방법으로는, O(n^2) 으로 배열을 두번 탐색할 수 있다. 하지만 비효율적.
  • 해시테이블에 중복값의 갯수를 저장. O(N)
    • 값을 0부터 최대배열값 100 까지 증가시키며, 중복갯수를 누적해서 더해간다.

해결

class Solution {
public:
    vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
        unordered_map<int, int> table; // nums[i], num of nums[i]
        for (int i = 0; i < nums.size(); i++) {
            table[nums[i]]++;
        }
        int nr_smaller = 0; // accumulate num of smaller one
        for (int i = 0; i < 101; i++) {
            if (table.find(i) != table.end()) {
                int tmp = table[i];
                table[i] = nr_smaller;
                nr_smaller = nr_smaller + tmp; // update nr_smaller
            }
        }
        for (int i = 0; i < nums.size(); i++) {
            nums[i] = table[nums[i]];
        }
        return nums;
        
    }
};
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글