[LeetCode] 80. Remove Duplicates from Sorted Array II

JEONG KI MIN·2025년 1월 8일

문제

80. Remove Duplicates from Sorted Array II

코드

생각해야할 예외 사항들이 꽤 많아서 시간이 좀 걸렸다.
예외 테스트케이스를 어떻게 잘 생각해야할지도 연습해야겠다..!

class Solution {
    public int removeDuplicates(int[] nums) {
        int x=0;
        int same = 1;
        int c=0;
        
        for(int i=1;i<nums.length;i++){
            if(nums[x] == nums[i]){
                same++;
                continue;
            } else {
                if(same >= 2){
                    for(int p=2;p<same;p++)
                        nums[x+p] = Integer.MAX_VALUE;
                }
                same = 1;
                x = i;
            }
        }
        
        if(same >= 2){
            for(int i = nums.length-same +2;i<nums.length;i++)
                nums[i] = Integer.MAX_VALUE;
        }

        Arrays.sort(nums);
        for(int k : nums){
            if(k!=Integer.MAX_VALUE)
                c++;
        }
        return c;
    }
}

일단 입력된 배열을 돌면서 몇개가 중복되어 입력되었는지 same 변수를 통해서 관리하고, 두개만 남기고 나머지는 전부 MAX_VALUE 로 바꾼다.

if(same >= 2){
    for(int i = nums.length-same +2;i<nums.length;i++)
        nums[i] = Integer.MAX_VALUE;
}

원래는 위의 코드가 없는 상태로 제출했는데 틀렸다. 예외 케이스는 다음과 같다.
[1,1,2,2,2,2] 와 같이 2번 이상 반복되는 숫자가 나오고, 그것과 다른 숫자는 나오지 않은 상태로 끝날때이다.

이를 관리하기 위해 same 변수가 2이상이면 업데이트 해주는 식으로 고쳤다.

profile
열심히 해볼게요

0개의 댓글