[LeetCode] Remove Duplicates from Sorted Array (JS)

nRecode·2020년 12월 15일
0

Algorithm

목록 보기
15/48

천천히... leetcode most interview 어쩌구 뽀개기 시작


문제

Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.

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

입출력 예
Input: nums = [1,1,2]
Output: 2, nums = [1,2]

접근

새로운 배열을 생성하지 않고 in place input은 배열이고 정렬되어 있는 상태이다. slice를 사용하는 방법 먼저 생각했다.

  1. i와 i + 1을 비교하여 slice? -> i는 1씩 증가하기 때문에 확실히 중복제거가 안된다.
    [0,0,0,1,1,2,2,2] 를 예로 들었을 때 최종 배열은 [0,0,1,2,2] 같은 식으로 return될 듯하다.
  2. i를 0이 아닌 length부터 시작할 경우 -> 계속 짤린다.
    [0,0,1,1,1,2,2,2] 중복은 잘 잡지만 마지막 결과는 [0]

그러다가 slice는 배열을 복사하기 때문에 in place가 아니라는 생각이 들었고 splice를 사용하였다.

  1. splice를 이용하여 i를 num의 length로 시작하는 방법!

풀이

var removeDuplicates = function(nums) {
  
    for(let i = nums.length - 1; i > 0; i--){
        if(nums[i] === nums[i - 1]) nums.splice(i, 1);
    }
    return nums.length;
};
profile
안정성, 확장성 있는 서버를 구축하고 가꾸는 개발자를 목표로 공부하고 있습니다. 🤔🤔🤔🤔 부족하기에 맞지 않는 내용이 있을 수 있습니다. 가감없이 피드백 해주시면 정말 감사하겠습니다..🙏

0개의 댓글