Leetcode/Top Interview 150

[Array/String][Medium] 80. Remove Duplicates from Sorted Array II

자전거통학 2024. 4. 28. 20:41

https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description

 

Q. 정렬된 정수배열 nums에서 해당 숫자를 최대 2번까지 nums에 출력하고 그 길이를 반환하라. 

 추가 메모리를 사용하지 말아라. 

 

Solution. 

 기존 로직들과 매우 유사하며, 다만 2회 check 로직을 추가 한다. 

 

public int RemoveDuplicates(int[] nums) 
{
    int idx = 1;
    int cnt = 1;
    int val = nums[0];
    for(int q = 1; q < nums.Length; ++q)
    {
        if(nums[q] == val)
        {
            ++cnt;
            if(cnt <= 2)
                nums[idx++] = nums[q];
        }
        else 
        {
            cnt = 1;
            val = nums[q];
            nums[idx++] = val;
        }
    }
    return idx;
}

 

 

적절한 결과.