[LeetCode][Java] Remove Duplicates from Sorted Array

최지수·2021년 11월 24일
0

Algorithm

목록 보기
28/77
post-thumbnail

문제

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

제한사항

  • 0 \leq nums.length \leq 3 * 10410^4
  • -100 \leq nums[i] \leq 100
  • nums is sorted in non-decreasing order.

접근

중복된 원소가 오름차순 정렬된 배열이 주어졌을 때 중복을 제거했을 경우의 원소 개수를 반환하고 그에 맞게 해당 범위 내 배열 값을 초기화하는 문제입니다.

Custom Judge에선 불필요한 원소는 뭐가 들어왔든 따로 체크하지 않는다니까 신경쓰지 않아도 되겠네요.

저는 단순하게 check 변수를 만들어 중복 초기화를 막아놨어요. 다만 배열의 경우 음수 인덱스를 가질 수 없어, 음수일 경우 최대값(100) - 값으로 해서 101~(-최대 음수값)을 인덱스로 지정해서 음수를 체크할 수 있게 전개했습니다.

답안

class Solution {
    public int removeDuplicates(int[] nums) {
        boolean[] checks = new boolean[201]; /* 0~100 : 양수, 101~200 : 음수 */

        int ret = 0;
        for(int i = 0; i < nums.length; ++i){
            int index = getIndex(nums[i]);
            if(checks[index])
                continue;

            checks[index] = true;
            nums[ret++] = nums[i];
        }
        return ret;
    }

    private int getIndex(int value){
        if(0 <= value)
            return value;
        return 100 - value;
    }
}
profile
#행복 #도전 #지속성

0개의 댓글