1. Description
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique elements appears only once. The relative order of the elements should be kept the same.
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 the duplicates, then the first k elements 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 sllocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
constraints :
- 1 <= nums.length <= 3 * 104
- -100 <= nums[i] <= 100
- nums is sorted in non-decreasing order.
2. Algorithms
Input list nums is sorted in non-decreasing order, but there are duplicates nums in list.
- Initiate pointer curr to store index without duplicates
- In for loop, check if value of nums[i-1] is not same the value of nums[i].
- In case, store the value of nums[i] into nums[curr] and update curr pointer +1.
- Return the curr
3. Codes
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if len(nums) == 1 : return 1
curr = 1
for i in range(1, len(nums)) :
if nums[i-1] != nums[i] :
nums[curr] = nums[i]
curr += 1
return curr
4. Conclusion
'LeetCode > Easy' 카테고리의 다른 글
28 Implement strStr() (0) | 2022.07.20 |
---|---|
27 Remove Elements (0) | 2022.07.19 |
21 Merged Two Sorted Lists (0) | 2022.07.19 |
20 Valid Parentheses (0) | 2022.07.19 |
14 Longest Common Prefix (0) | 2022.07.12 |