26. Remove Duplicates from Sorted Array
Source
https://leetcode.com/problems/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
Code
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function (nums) {
const dict = {};
let i = 0;
while (true) {
if (i > nums.length) {
break;
}
if (Object.keys(dict).includes(String(nums[i]))) {
nums.splice(i, 1);
} else {
dict[nums[i]] = true;
i++;
}
}
};
How to solve?
객체 dict를 선언하고 while loop를 실행한다.
Object.keys(obj).includes(String(nums[i]))) 를 사용해서 Object에 해당 key가 있는지 확인 하고 있다면 nums에 해당 숫자를 삭제한다. 없다면 dict에 해당 값을 추가하고 i에 1을 더한다.
생각이 나는 대로 풀어보았는데 놀라울 정도로 성능이 안좋았다.
단순히 문제를 푸는 것이 아니라 효율을 생각해야 한다는 것을 다시 한번 상기한다.
Reviewing the best code
const removeDuplicates = (nums) => {
if (nums.length === 0) return 0;
let i = 0;
for (let j = 1; j < nums.length; j++) {
if (nums[j] === nums[i]) continue;
// If the elements are equal then continue
// else copy the unique element by then to "i+1" position
nums[++i] = nums[j];
}
return i + 1;
};
정렬된 nums 뒤에 무엇이 와도 상관이 없기 때문에 for문으로 순회하며
새로운 값이 nums에 나올 때 마다 앞에서부터 업데이트 해준다.
'Problem solve' 카테고리의 다른 글
[Leetcode] 34. Find First and Last Position of Element in Sorted Array (JavaScript) (0) | 2023.06.10 |
---|---|
[Leetcode] 27. Remove Element (JavaScript) (0) | 2023.06.09 |
[Leetcode] 48. Rotate Image (Python) (0) | 2023.05.15 |
[Leetcode] 11. Container With Most Water (JavaScript) (0) | 2023.05.07 |
[Leetcode] 28. Find the Index of the First Occurrence in a String (JavaScript) (0) | 2023.05.06 |