Last active
October 26, 2019 00:15
-
-
Save yitonghe00/2fdc4d9cd51c1e4f5879f8704d7d0e98 to your computer and use it in GitHub Desktop.
80. Remove Duplicates from Sorted Array II (https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/): Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Two pointer: read/write pointers (slow/fast pointers) | |
// Time: O(n), 0ms | |
// Space: O(1), 37.2mb | |
class Solution { | |
public int removeDuplicates(int[] nums) { | |
// Corner cases | |
if(nums.length < 3) return nums.length; | |
int w = 2, r = 2; | |
// Read pointer moves every loop | |
for(; r < nums.length; r++) { | |
if(nums[r] > nums[w - 2] ) { | |
// !!: Write when we won't make 3 dups in a row | |
nums[w++] = nums[r]; | |
} | |
} | |
return w; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Two pointer: read/write pointers (slow/fast pointers) | |
// Time: O(n), 0ms | |
// Space: O(1), 37.3mb | |
class Solution { | |
public int removeDuplicates(int[] nums) { | |
int i = 0; //i is slow pointer | |
for (int n : nums) //n is fast pointer | |
if (i < 2 || n > nums[i-2]) //When slow is not the third in a row | |
nums[i++] = n; //Assign fast to slow | |
return i; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment