Leetcode 26. Remove Duplicates from Sorted Array

juniping·2025년 2월 18일
0

문제

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. Then return the number of unique elements in nums.
Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
  • Return k.

정리

  • 투포인터 문제
  • 새로 정렬되는 배열의 인덱스 하나와 기존 배열을 탐색하는 인덱스 하나를 설정한다
  • in-place(in-place algorithm) : 추가적인 메모리 공간을 거의 사용하지 않고, 주어진 배열이나 데이터 구조 내에서 직접 값을 변경하여 문제를 해결하는 알고리즘
  • in-place로 풀어야하기 때문에 기존 배열을 재배치하는 방식으로 문제를 푼다.
  • 배열을 탐색하며 이전 값과 같지 않은 경우만 새로 정렬되는 인덱스의 값으로 설정하고 인덱스를 추가해준다.

풀이

class Solution {
    public int removeDuplicates(int[] nums) {

        if(nums.length==0){
            return 0;
        }

        int index = 1;

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

결과

profile
도전, 영원한 젊음

0개의 댓글