본문 바로가기

LeetCode - Top Interview 150

[Java Script]LeetCode 26. Remove Duplicates from Sorted Array

1. 문제 개요

문제 링크 : 26. Remove Duplicates from Sorted Array

 

Remove Duplicates from Sorted Array - LeetCode

Can you solve this real interview question? Remove Duplicates from Sorted Array - Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place [https://en.wikipedia.org/wiki/In-place_algorithm] such that each unique element ap

leetcode.com

  • 주어지는 1개의 배열(nums)에서 중복값을 제거하시오

2. 문제 풀이

배열 내에서 중복값을 제거하면 되는문제

해결 방법으로는 배열을 탐색하면서 중복되는 값을 제거하는 방법과 중복을 허용하지않는 다른 자료 구조로 변환하는 방법이 있습니다.

저는 후자를 이용하여 구현 하였습니다

 

이를 구현하기 위해 주석으로 코드의 구조를 잡아보면 다음과 같다.

var removeDuplicates = function(nums) {
	// nums 배열을 이용하여 Set 생성
	// 중복값이 사라진 Set을 다시 배열로 생성(기존 배열에 대입)
    // 남은 배열의 원자수를 반환
};

LeetCode 요구 양식으로 코드 구현

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function(nums) {
    let arrToSet = [...new Set(nums)]
    nums.splice(arrToSet.length);    
    for(let i=0; i<arrToSet.length; i++) { 
        if(i == 0) nums.slice(0, arrToSet.length);
        nums[i] = arrToSet[i];
    }
    return nums.length;
};

LeetCode 제출 결과

 

3. 시간 복잡도 계산

더보기

O(n) = O(n

 

4. 개선 사항

splice 기능을 직접 구현하면 조금도 속도와 메모리 쪽 기능 개선의 여지가 있었을 듯합니다.

 

5. 깃허브

관련 사항은 깃허브에 모두 기재되어 있습니다.