문제
정수 배열 nums와 정수 val이 주어지면 nums에서 val의 모든 항목을 제자리에서 제거합니다. 요소의 상대적 순서는 변경될 수 있습니다.
일부 언어에서는 배열의 길이를 변경할 수 없으므로 결과를 배열 nums의 첫 번째 부분에 배치해야 합니다. 더 공식적으로, 중복을 제거한 후 k 요소가 있으면 nums의 처음 k 요소가 최종 결과를 보유해야 합니다. 처음 k개 요소를 넘어 무엇을 남겨두는지는 중요하지 않습니다.
nums의 처음 k 슬롯에 최종 결과를 배치한 후 k를 반환합니다.
다른 어레이에 추가 공간을 할당하지 마십시오. O(1) 추가 메모리를 사용하여 제자리에서 입력 배열을 수정하여 이 작업을 수행해야 합니다.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
// It is sorted with no values equaling val.
int k = removeElement(nums, val); // Calls your implementation
assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.
Example 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).
Example 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).
Constraints:
- 0 <= nums.length <= 100
- 0 <= nums[i] <= 50
- 0 <= val <= 100
제출코드
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
let count = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== val) {
nums[count] = nums[i];
count++;
}
}
return count;
};
풀이
val로 주어진 정수의 값과 현재 인덱스의 들어있는값이 같은지만 확인해주면된다.
만약 다르다면 nums의 0번째 인덱스부터 차례로 대입하면된다.
'Computer Science > 코딩테스트' 카테고리의 다른 글
LeetCode #70 Climbing Stairs(EASY) (0) | 2022.07.19 |
---|---|
LeetCode #6 Zigzag Conversion (0) | 2022.07.12 |
LeetCode #26 Remove Duplicates from Sorted Array (0) | 2022.07.12 |
LeetCode #5 Longest Palindromic Substring (0) | 2022.07.12 |
LeetCode #21 Merge Two Sorted Lists (0) | 2022.07.12 |