80. Remove Duplicates from Sorted Array II
2017-02-27 09:32
239 查看
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums =
Your function should return length =
It doesn't matter what you leave beyond the new length.
开始的思路是:从前向后遍历,遇到前后相等的就用while跳过,代码如下:
public class Solution {
public int removeDuplicates(int[] nums) {
int len = 0, count = 0;
if (nums.length < 3) {
return nums.length;
}
for (int i = 0; i < nums.length; i ++) {
if (i != 0 && nums[i] == nums[i - 1]) {
while (i < nums.length && nums[i] == nums[i - 1])
i ++;
nums[len ++] = nums[i - 1];
}
if (i < nums.length)
nums[len ++] = nums[i];
}
return len;
}
}而后看到一种优秀的解法:
public int removeDuplicates(int[] nums) {
int i = 0;
for (int n : nums)
if (i < 2 || n > nums[i-2])
nums[i++] = n;
return i;
}这样做可以推广到任意的允许x遍重复,只需把判断条件if (i < 2 || n > nums[i-2])修改成if (i < x || n > nums[i-x])。
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,
2and
3.
It doesn't matter what you leave beyond the new length.
开始的思路是:从前向后遍历,遇到前后相等的就用while跳过,代码如下:
public class Solution {
public int removeDuplicates(int[] nums) {
int len = 0, count = 0;
if (nums.length < 3) {
return nums.length;
}
for (int i = 0; i < nums.length; i ++) {
if (i != 0 && nums[i] == nums[i - 1]) {
while (i < nums.length && nums[i] == nums[i - 1])
i ++;
nums[len ++] = nums[i - 1];
}
if (i < nums.length)
nums[len ++] = nums[i];
}
return len;
}
}而后看到一种优秀的解法:
public int removeDuplicates(int[] nums) {
int i = 0;
for (int n : nums)
if (i < 2 || n > nums[i-2])
nums[i++] = n;
return i;
}这样做可以推广到任意的允许x遍重复,只需把判断条件if (i < 2 || n > nums[i-2])修改成if (i < x || n > nums[i-x])。
相关文章推荐
- leetcode-26&80 Remove Duplicates from Sorted Array I&II
- Lettcode_80_Remove Duplicates from Sorted Array II
- 80 Remove Duplicates from Sorted Array II
- LeetCode26/27/80/75 Remove Duplicates from Sorted Array I and II/Remove Element/Set Colors**
- leetcode || 80、Remove Duplicates from Sorted Array II
- 【leetcode c++】80 Remove Duplicates from Sorted Array II
- 80 Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- Leetcode 80]Remove Duplicates from Sorted Array II
- Leetcode_80_Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- LeetCode 80 Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- leetcode[80] Remove Duplicates from Sorted Array II
- LeetCode(80) Remove Duplicates from Sorted Array II
- LeetCode80 Remove Duplicates from Sorted Array II
- Medium 80题 Remove Duplicates from Sorted Array II
- leetcode 80 Remove Duplicates from Sorted Array II
- leetcode80 Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II