Last active
January 1, 2016 12:19
-
-
Save wayetan/8144218 to your computer and use it in GitHub Desktop.
Remove Duplicates from Sorted Array
This file contains hidden or 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
| /** | |
| * 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 A = [1,1,2], | |
| * Your function should return length = 2, and A is now [1,2]. | |
| */ | |
| public class Solution { | |
| public int removeDuplicates(int[] A) { | |
| int len = A.length; | |
| int i = 0; | |
| if(len <= 1) | |
| return len; | |
| for(int j = 1; j < len; j++){ | |
| if(A[j] != A[i]) | |
| A[++i] = A[j]; | |
| } | |
| return i + 1; | |
| } | |
| } |
This file contains hidden or 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
| /** | |
| * Follow up for "Remove Duplicates": | |
| * What if duplicates are allowed at most twice? | |
| * For example, | |
| * Given sorted array A = [1,1,1,2,2,3], | |
| * Your function should return length = 5, and A is now [1,1,2,2,3]. | |
| */ | |
| public class Solution { | |
| public int removeDuplicates(int[] A) { | |
| int len = A.length; | |
| int count = 1; | |
| int i = 0; | |
| if(len <= 2) | |
| return len; | |
| for(int j = 1; j < len; j++){ | |
| if(A[j] == A[i]){ | |
| // count the difference | |
| if(count < 2){ | |
| count++; | |
| A[++i] = A[j]; | |
| } | |
| } else { | |
| count = 1; | |
| A[++i] = A[j]; | |
| } | |
| } | |
| return i + 1; | |
| } | |
| //better one: | |
| public int removeDuplicates(int[] nums) { | |
| int len = nums.length; | |
| if(len < 3) return len; | |
| int i = 1; | |
| for(int j = 2; j < len; j++) { | |
| if(nums[j] != nums[i] || nums[j] != nums[i - 1]) | |
| nums[++i] = nums[j]; | |
| } | |
| return i + 1; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment