(Array / String) Remove Duplicates from Sorted Array II

송재호·2025년 8월 17일
0

https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/?envType=study-plan-v2&envId=top-interview-150

자바는 원본 배열도 같이 정렬해서 줘야하나보다.
일단 위 내용 생각해서 푼건 아래와 같음

class Solution {
    public int removeDuplicates(int[] nums) {
        
        int prev = Integer.MAX_VALUE;
        int cnt = 0;

        for (int i=0; i<nums.length; i++) {
            int current = nums[i];
            if (prev == current) {
                if (cnt >= 2) {
                    nums[i] = Integer.MAX_VALUE;
                } else {
                    cnt++;
                }
            } else {
                prev = current;
                cnt = 1;
            }
        }

        Arrays.sort(nums);

        int k = 0;
        for (int i=0; i<nums.length; i++) {
            if (nums[i] == Integer.MAX_VALUE) {
                break;
            }
            k++;
        }
        return k;
    }
}

어거지로 푼 느낌이라서 솔루션 참고했다.
논리적으로 한 숫자는 at most twice이므로 투포인터로 찾을 수 있나봄

핵심은 rightleft - 2 인덱스의 비교인데, 최대 2번까지 이어질 수 있으므로 이게 다르다면

  • left와 right는 2부터 시작, 처음 두 요소는 유효하다고 가정
  • rightleft - 2와 비교
    • 같으면: 해당 요소가 세 번째 등장한다는 뜻이므로 무시해야 함
    • 다르면: 해당 요소가 결과에 포함될 수 있음
class Solution {
    public int removeDuplicates(int[] nums) {
        int left = 2;
        for (int right=2; right<nums.length; right++) {
            if (nums[right] != nums[left - 2]) {
                nums[left] = nums[right];
                left++;
            }
        }
        return left;
    }
}
profile
식지 않는 감자

0개의 댓글