Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add RemoveDuplicatesfromSortedArray2 #63

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
43 changes: 43 additions & 0 deletions Medium/RemoveDuplicatesfromSortedArray2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* Remove Duplicates from Sorted Array II
* Follow up for "Remove Duplicates":
* What if duplicates are allowed at most twice?
* For example,
* Given sorted array nums = [1,1,1,2,2,3],
* Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
* Note: create a countEach variable to count duplicated times for each integer in array.
* Time complexity = O(n)
* @author chenshuna
*/

public class RemoveDuplicatesfromSortedArray2 {
public static int removeDuplicates(int[] nums) {
int res = 1;
if(nums.length <= 1){
return nums.length;
}
int countEach = 1;
for(int i = 1; i<nums.length; i++){
if(nums[i] == nums[i-1] && countEach < 2){
nums[res] = nums[i];
countEach++;
res++;
}
else if(nums[i] != nums[i-1]){
nums[res] = nums[i];
res++;
countEach = 1;
}
else{
countEach++;
}
}
return res;
}

public static void main(String[] args) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here the indention is different from my local file.

// TODO Auto-generated method stub
int[] res = {1,1,1,2,3};
System.out.print(removeDuplicates(res));
}
}