본문 바로가기
Algorithm

[leetCode 80번] Remove Duplicates from Sorted Array II (Java)

by ddahu 2023. 8. 24.

1.문제

LeetCode - The World's Leading Online Programming Learning Platform

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


2. 문제 설명

 

이 문제는 중복된 요소는 제거 하되 최대 2개까지 허용하는 문제이다.


3. 소스코드 

class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length <= 2) {
        return nums.length;
    }

    int idx = 2;
    for (int i = 2; i < nums.length; i++) {
        if (nums[i] != nums[idx - 2]) {
            nums[idx] = nums[i];
            idx++;
        }
    }
    
    return idx;
    }
}

4. 문제 설명

 

이 문제도 기본적인 배열의 요소를 삭제 하는데 코드에서 조금만 수정 하면 된다.

 

배열이 기본 두개 일경우 예외를 처리하고

 

중복을 제거하는데 사용하는 hashSet , Set 과 다르게 이문제는 2개를 허용하기 때문에 직접 배열의 요소를 컨트롤 하는 부분이 좋아 보인다.

 

배열의 요소중 idx = 2 이전에 이미 존재하는지 여부를 체크하고 있으면 제거하는 식으로 진행 하면 어려움이 없다.