[LeetCode] 26. Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums =
Given input array nums =
[1,1,2]
,
Your function should return length =
2
, with the first two elements of nums being 1
and 2
respectively. It doesn't matter what you leave beyond the new length.
Thought process:
Because what I leave beyond the new length doesn't matter, I can overwrite the duplicate elements with the unique elements. The idea is to iterate through the array and keep a count of duplicate elements seen so far. If we see a duplicate element, we increment the count. Otherwise, we write the element into its right position.
Solution 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Solution { public: int removeDuplicates(vector<int>& nums) { int duplicates = 0; for (int i = 1; i < nums.size(); i++) { if (nums[i] == nums[i - 1]) { duplicates++; } else { nums[i - duplicates] = nums[i]; } } return nums.size() - duplicates; } }; |
Here's a two pointers solution:
Solution 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class Solution { public int removeDuplicates(int[] nums) { int i = 0; for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[j - 1]) { i++; } nums[i] = nums[j]; } return i + 1; } } |
Time complexity: O(n). Space complexity: O(1).
Comments
Post a Comment