알고리즘🅰/리트코드

[리트코드] 26. Remove Duplicates from Sorted Array

개발조각 2022. 9. 25. 15:45
728x90
반응형

안녕하세요. 개발조각입니다.😊

이번 문제는 솔직히 말자체가 이해가 안 가서 검색해서 찾아봤어요.

아마 제블로그를 보신다면 저와 같이 문제 자체가 이해가 안 가서 보신 분들이겠죠?


https://leetcode.com/problems/remove-duplicates-from-sorted-array/

 

Remove Duplicates from Sorted Array - LeetCode

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

 

아래 블로그를 참고해서 풀었습니다.

https://redquark.org/leetcode/0026-remove-duplicates-from-sorted-array/

 

LeetCode #26 - Remove Duplicates In Sorted Array

Hello happy people 👋! Let’s look at another LeetCode problem today. Remove Duplicates From Sorted Array Problem Statement Given a sorted array , remove the duplicates in-place such that each element appears only once and returns the new length. Do not

redquark.org


이문제를 읽어보시면 아래와 같은 내용이 있습니다.

(파파고 써서 번역했습니다.)

"다른 어레이에 추가 공간을 할당하지 마십시오. O(1) 추가 메모리를 사용하여 입력 배열을 수정해야 합니다."

 

  • 다른 어레이에 추가 공간을 할당하지 마십시오. → 새로운 배열을 만들지 말라
  • O(1) 추가 메모리를 사용하여 입력 배열을 수정해야 합니다. → for문 써라

이 말인 것 같아요.

 

 

이문제를 풀어보았을 때 이것저것 대입해보았는데요.

단순히 nums의 배열에서 중복을 제거하라는 문제 같아서

다른 방법(set, filter 등등)으로 중복을 제거하는 방법으로 풀어봤더니

다 다른 배열을 추가하는 방식이라 오류가 나더라고요.

→ 결론은 for문 써라

 

그럼 for문을 어떻게 쓸지 설명하자면

아래와 같이 코드를 작성하면

var removeDuplicates = function(nums) {
    return 3 // [0, 1, 2]
};

 

이렇게 나옵니다.

 

예제 1

Input: nums = [1,1,2]

예제 2

Input: nums = [0,0,1,1,1,2,2,3,3,4]

결국 이문제는 nums배열에서 중복을 제거한 배열의 길이를 구하면 됩니다.

예제 1은 return 2

예제 2는 return 5

 

 

그리고 예제 1, 2를 보시면

중복 원소가 뒤죽박죽 섞여있는 게 아니라 오름차순으로 이쁘게 정렬이 되어있습니다.

이점을 활용해서 for문에 적용을 시키면 됩니다.

뭘 적용하라는 건지는 코드를 보시면 바로 아실 것 같아요.


해결방안

var removeDuplicates = function(nums) {
    let count = 0;
    for(let i=0; i< nums.length; i++){        
        if(nums[i] !== nums[i+1]){
            nums[count] = nums[i];
            count++;
        }
    }
    return count;
};

 

 

728x90
반응형