LeetCode | Remove Duplicates from Sorted Array II
2014-11-03 17:31
399 查看
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A =
Your function should return length =
注解:注意右边的程序是有错误的。
由于题目允许在数组中重复两次,且数组是sorted的,故每次for循环取A[i]与它前面的前面相比较,如果两者相等,则中间的肯定也相等,即为一个不符合要求的三重复。但注意:不能写成右边的 A[i]!=A[i-2]形式。
举例:数组1 1 1 2 2 3
在i=3的循环后,数组变为 1 1 2 2 2 3,length=3,A[2]=2,而prepre是前一次i=3循环时由pre赋给的,prepre=原A[2]=1,这点很重要。
在i=4的循环时,判断A[4]!=prepre,而不是判断A[4]!=A[2],否则只有一个三重复的数组由于判断A[2]=A[4]而又导入了一个额外的三重复。
prepre与pre是用来在消除重复赋值前保存原数组的值的。
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].
//思想类似于前天的去数组重复,用length标记满足重复最多允许两次的数组的长度 public class Solution { public int removeDuplicates(int[] A) { if (A.length <= 2) return A.length; int length = 2; int prepre = A[0]; int pre = A[1]; for (int i=2; i<A.length; i++){ // for (int i=2; i<A.length; i++){ if (A[i] != prepre){ // if (A[i] != A[i-2]){ A[length++] = A[i]; // A[length++] = A[i]; } // } prepre = pre; // } pre = A[i]; } // return length; return length; } }
注解:注意右边的程序是有错误的。
由于题目允许在数组中重复两次,且数组是sorted的,故每次for循环取A[i]与它前面的前面相比较,如果两者相等,则中间的肯定也相等,即为一个不符合要求的三重复。但注意:不能写成右边的 A[i]!=A[i-2]形式。
举例:数组1 1 1 2 2 3
在i=3的循环后,数组变为 1 1 2 2 2 3,length=3,A[2]=2,而prepre是前一次i=3循环时由pre赋给的,prepre=原A[2]=1,这点很重要。
在i=4的循环时,判断A[4]!=prepre,而不是判断A[4]!=A[2],否则只有一个三重复的数组由于判断A[2]=A[4]而又导入了一个额外的三重复。
prepre与pre是用来在消除重复赋值前保存原数组的值的。
相关文章推荐
- Leetcode: Remove Duplicates from Sorted Array II
- leetcode: 80. Remove Duplicates from Sorted Array II
- LeetCode Remove Duplicates from Sorted Array II
- LeetCode:Remove Duplicates from Sorted Array II
- 080 Remove Duplicates from Sorted Array II [Leetcode]
- 【LeetCode】Remove Duplicates from Sorted Array I && II
- LeetCode No.80 Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II 有序数组中去除重复项之二
- Leetcode_Remove Duplicates from Sorted Array II
- Leetcode NO.80 Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode 80 --- Remove Duplicates from Sorted Array II
- LeetCode 80 Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II - Leetcode
- leetcode_80题——Remove Duplicates from Sorted Array II(两个指针)
- Remove Duplicates from Sorted Array II ——LeetCode
- leetcode刷题系列C++-Remove Duplicates From Sorted Array II
- leetcode -- Remove Duplicates from Sorted Array II
- Leetcode 80]Remove Duplicates from Sorted Array II
- [leetcode 80, Medium] Remove Duplicates from Sorted Array II