본문 바로가기
LeetCode/코딩 테스트 스터디 2주차

[LeetCode] 26. Remove Duplicates from Sorted Array 풀이 (JS)

by inwoo1324 2022. 7. 17.

0. 문제

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

중복을 제거한 배열 원소의 수를 구하고 기존 배열의 순서대로 해당 값을 나열하는 문제

#1
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
#2
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

 

1.언어

자바스크립트(JavaScript)

 

2. 문제 풀이

var removeDuplicates = function(nums) {
    let cnt = 0, val = null;
    for (let i=0; i<nums.length; i++){
        if (nums[i] != val){
            val = nums[i]
            nums[cnt++] = val
        }
    }
    return cnt
};
Runtime: 99 ms, faster than 74.39% of JavaScript online submissions for Remove Duplicates from Sorted Array.
Memory Usage: 44.5 MB, less than 68.99% of JavaScript online submissions for Remove Duplicates from Sorted Array.
 

중복문자는 변수 val로 검사하고 아닐 시 변수 cnt를 1씩 더하며 해당 값을 나열한다.