0. 문제
https://leetcode.com/problems/remove-element/
Remove Element - 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 = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
#2
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).
1.언어
자바스크립트(JavaScript)
2. 문제 풀이
var removeElement = function(nums, val) {
let cnt = 0
for (let i = 0; i < nums.length; i++) {
if (nums[i] != val){
nums[cnt++] = nums[i]
}
}
return cnt
};
Runtime: 67 ms, faster than 88.06% of JavaScript online submissions for Remove Element.
Memory Usage: 41.9 MB, less than 67.82% of JavaScript online submissions for Remove Element.
반복문으로 배열 요소를 하나씩 정수와 비교 후 아닐 시 변수 cnt를 1씩 더하며 해당 값을 나열한다.
'LeetCode > 코딩 테스트 스터디 2주차' 카테고리의 다른 글
[LeetCode] 28. Implement strStr() 풀이 (JS) (0) | 2022.07.17 |
---|---|
[LeetCode] 6. Zigzag Conversion 풀이 (JS) (0) | 2022.07.17 |
[LeetCode] 26. Remove Duplicates from Sorted Array 풀이 (JS) (0) | 2022.07.17 |
[LeetCode] 5. Longest Palindromic Substring 풀이 (JS) (0) | 2022.07.17 |
[LeetCode] 21. Merge Two Sorted Lists 풀이 (JS) (0) | 2022.07.17 |