본문 바로가기
🧩 Algorithm

LeetCode : 26. Remove Duplicates from Sorted Array

by iirin 2023. 8. 25.

문제 링크

 

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

문제 먼저 읽기

  • 정수 배열 nums는 오름차순으로 정렬되어 주어진다.
  • 중복된 요소를 제거하자. 요소의 상대적인 순서는 동일하게 유지해야 한다.
    • nums를 변경해야한다. 고유 요소 수보다 큰 index의 나머지 요소는 상관없다.
  • 고유 요소 수를 정수 반환한다.

 

어떻게 풀까?

생각

  • 같은 방식으로 포인터로 풀되, 이전 수를 저장해놓았다가 비교할 수 있도록 해보면 어떨까?

수도코드

class Solution {
    public int removeDuplicates(int[] nums) {
        int curl = 1;
        int ex = nums[0];
        for (int p=1; p<nums.length; p++) {
            if (ex!=nums[p]) {
                nums[curl++] = nums[p];
            }
            ex = nums[p]; // 이전 번호를 업데이트 해준다.
        }
        return curl;
    }
}

결과

다른 풀이 방식과 문제 회고

class Solution {
    public int removeDuplicates(int[] nums) {
        int i = 0;
        for(int j = 1; j<nums.length ; j++){
            if(nums[i] != nums[j]){
                nums[i+1] = nums[j];
                i++;
            }
        }

        return i+1;
    }
}
  • 변수를 줄여 memory 효율을 개선한 것 같다.