1. Description
Given an integer array nums and an integer val, remove all occurences of val in nums in-place. The relative order of the elements may be changed.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing dupliactes, then the first k elemgnets of nums should hold the final result. It does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of nums.
Do not allocate extra space for another array. You must do this by modifying the input arry in-pace with O(1) extra memory.
constraints :
- 0 <= nums.length <= 100
- 0 <= nums[i] <= 50
- 0 <= val <= 100
2. Algorithms
This problems looks similar to problem "Remove duplicates elements from array".
- Initialize curr pointer to store index for non val values.
- In for loop, check if the value of current value is same with val.
- If there is difference, store the value of current value into nums[curr] and update curr by +1.
3. Codes
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
if len(nums) == 0 : return 0
curr = 0
for i in range(0, len(nums)) :
if nums[i] != val :
nums[curr] = nums[i]
curr += 1
return curr
4. Conclusion
'LeetCode > Easy' 카테고리의 다른 글
35 Search Insert Position (0) | 2022.07.20 |
---|---|
28 Implement strStr() (0) | 2022.07.20 |
26 Remove Duplicates from Sorted Array (0) | 2022.07.19 |
21 Merged Two Sorted Lists (0) | 2022.07.19 |
20 Valid Parentheses (0) | 2022.07.19 |