중복된 값을 제거하기에는 Set()이 제일 효율적이라고 생각했다.
Set()을 사용한 김에 무엇이고 어떻게 사용하는지 알아보겠습니다.
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
let unique = new Set()
let index = 0
for(let i=0;i < nums.length;i++){
if(!unique.has(nums[i])){
unique.add(nums[i])
nums[index]=nums[i]
index++
}
}
return index
};
Set 이란?
- value값 만을 저장하며 중복을 허용하지 않는 Collection 입니다.
- 대소문자를 구분합니다.
왜 사용할까?
- value값으로 고유한 값을 가질 수 있습니다.
- 중복값을 제거할 수 있습니다.
- 배열과 같이 반복문으로 사용할수 있습니다 : for (const i of set){} -> set.key() / set.values()가능
-> 그러나 push, pop등 사용 못함
메서드
.add()
.delete()
.has()
.size()
.clear()
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
'코테' 카테고리의 다른 글
LeetCode Top Interview 150 - 80. Remove Duplicates from Sorted Array II (0) | 2023.08.24 |
---|---|
LeetCode Top Interview 150 - 121. Best Time to Buy and Sell Stock (0) | 2023.08.24 |
LeetCode Top Interview 150 - 80. Remove Duplicates from Sorted Array II (0) | 2023.08.23 |
LeetCode Top Interview 150 - 169. Majority Element (0) | 2023.08.23 |
LeetCode Top Interview 150 - 27. Remove Element (0) | 2023.08.23 |