[Leetcode] 27. Remove Element (JavaScript)
Source
https://leetcode.com/problems/remove-element/
Remove Element - LeetCode
Can you solve this real interview question? Remove Element - Given an integer array nums and an integer val, remove all occurrences of val in nums in-place [https://en.wikipedia.org/wiki/In-place_algorithm]. The order of the elements may be changed. Then r
leetcode.com
Code
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function (nums, val) {
let left = 0;
let right = nums.length - 1;
while (left <= right) {
if (nums[right] === val) {
nums.splice(right, 1);
}
if (nums[left] === val) {
nums.splice(left, 1);
left -= 1;
}
left += 1;
right -= 1;
}
return nums.length;
};
How to solve?
해당 문제는 val을 찾아 nums에서 제거한 뒤 nums의 길이를 반환 해주는 문제이다.
또한 in-place (원본 자료구조에 비해 아주 작은 메모리만을 사용하여 문제를 해결) 알고리즘이다.
nums에서 val을 찾아야 하는데 배열이 정렬되어 있지 않기 때문에 two pointer를 사용해 연산 속도를 줄여주었다.
Reviewing the best code
https://leetcode.com/problems/remove-element/solutions/3250750/java-script-3-line-solution-beats-99/
Java Script 3 line Solution beats 99% - Remove Element - LeetCode
View SDK006's solution of Remove Element on LeetCode, the world's largest programming community.
leetcode.com
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
while(nums.indexOf(val) !== -1) {
nums.splice(nums.indexOf(val), 1)
}
return nums.length;
};
해당 코드는 자바스크립트의 indexOf()함수를 사용해서 문제를 빠르게 해결했다.
내장 함수를 잘 알고 사용하는 것도 중요하다는 것을 배웠다.
'Problem solve' 카테고리의 다른 글
[Leetcode] 34. Find First and Last Position of Element in Sorted Array (JavaScript) (0) | 2023.06.10 |
---|---|
[Leetcode] 26. Remove Duplicates from Sorted Array (0) | 2023.05.16 |
[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 |