알고리즘 문제/LeetCode

LeetCode - Remove Duplicates from Sorted Array II (C#)

우대비 2025. 3. 6. 10:19
반응형

 

정렬된 배열을 입력 받을 때, 중복 개수가 최대 2가 되도록 중복 요소들을 제거해주세요.

 


📗 풀이 방법

// 숫자, 중복 개수
Dictionary<int, int> dic = new Dictionary<int, int>();

중복 개수를 빠르게 파악하기 위해 Dicrionary를 사용합니다 

 

for (int i = 0; i < nums.Length; i++)
{
    if (!dic.ContainsKey(nums[i]))
        dic.Add(nums[i], 0);
    dic[nums[i]]++;
 }

nums 배열을 순회하며 Dictionary에 넣어주고 개수를 + 1 해줍니다.


📜 목표

우리가 구해야 하는 목표는 최대 중복 개수가 2가 되도록 만든 후의 nums 배열과 nums배열의 길이입니다.

중복 개수가 2이하인 것들만 nums 배열에 남을 수 있으니 가상의 index를 만들어서 관리해줍니다.

 

int ret = 0;
int idx = 0;
for (int i = 0; i < nums.Length; i++)
{
    if (!dic.ContainsKey(nums[i]))
        dic.Add(nums[i], 0);

    dic[nums[i]]++;
    if (dic[nums[i]] <= 2)
    {
        ret++;
        nums[idx++] = nums[i]; 
    }
}

중복 개수가 2 이하인 경우 재배치를 해주며 해결합니다. 그리고, 재배치한 횟수를 기록하여 반환해줍니다.

 

 

 


🔹정답 코드

public int RemoveDuplicates(int[] nums)
{
    int ret = 0;
    Dictionary<int, int> dic = new Dictionary<int, int>();

    int idx = 0;
    for (int i = 0; i < nums.Length; i++)
    {
        if (!dic.ContainsKey(nums[i]))
            dic.Add(nums[i], 0);

        dic[nums[i]]++;
        if (dic[nums[i]] <= 2)
        {
            ret++;
            nums[idx++] = nums[i]; 
        }
    }

    return ret;
}

 

 

반응형
LIST

'알고리즘 문제 > LeetCode' 카테고리의 다른 글

Longest Increasing Subsequence (C#)  (0) 2025.02.04
Flood Fill (C#)  (0) 2025.02.04
Largest Rectangle in Histogram (C#)  (0) 2025.02.03