题目:
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.
链接: http://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
题解:
在排好序的数组里最多保留两个重复数字。设置一个limit,使用一个count,一个result用来计算最终结果。依照count和limit的关系决定是否移动到下一个index。
Time Complexity - O(n), Space Complexity - O(1)。
public class Solution { public int removeDuplicates(int[] nums) { if(nums == null || nums.length == 0) return 0; int limit = 2, count = 1, result = 0; for(int i = 0; i < nums.length; i ++){ if(i > 0 && nums[i] == nums[i - 1]) count ++; else count = 1; if(count <= limit) nums[result ++] = nums[i]; } return result; } }
Update:
public class Solution { public int removeDuplicates(int[] nums) { if(nums == null || nums.length == 0) return 0; int count = 1, index = 1; for(int i = 1; i < nums.length; i++) { if(nums[i] == nums[i - 1]) count ++; else count = 1; if(count <= 2) nums[index++] = nums[i]; } return index; } }
二刷:
就是设置一个limit,设置当前count为1,用来返回结果的index为1.
每次在循环里尝试更新count, 假如nums[i] = nums[i - 1]则count++,否则count = 1
在count <= limit的条件下,我们可以更新num[index++] = nums[i]。
最后返回index
Java:
Time Complexity - O(n), Space Complexity - O(1)。
public class Solution { public int removeDuplicates(int[] nums) { int limit = 2, count = 1, index = 1; for (int i = 1; i < nums.length; i++) { count = nums[i] == nums[i - 1] ? count + 1 : 1; if (count <= limit) { nums[index++] = nums[i]; } } return index; } }
三刷:
几天没刷题,大脑反应速度就不够了,想得也细致,不能透过现象看本质。
Java:
public class Solution { public int removeDuplicates(int[] nums) { if (nums == null || nums.length == 0) return 0; int k = 2, count = 1, lo = 1; for (int i = 1; i < nums.length; i++) { if ((nums[i] == nums[i - 1] && count < k) || (nums[i] != nums[i - 1])) { count = (nums[i] == nums[i - 1]) ? count + 1 : 1 ; nums[lo++] = nums[i]; } } return lo; } }
Update:
使用二刷的逻辑
public class Solution { public int removeDuplicates(int[] nums) { if (nums == null || nums.length == 0) return 0; int limit = 2, count = 1, lo = 1; for (int i = 1; i < nums.length; i++) { count = (nums[i] == nums[i - 1]) ? count + 1 : 1 ; if (count <= limit) nums[lo++] = nums[i]; } return lo; } }
Update:
使用Stefan的代码
public class Solution { public int removeDuplicates(int[] nums) { int i = 0; for (int num : nums) { if (i < 2 || num > nums[i - 2]) { nums[i++] = num; } } return i; } }
Reference:
https://leetcode.com/discuss/42348/3-6-easy-lines-c-java-python-ruby