您的位置:首页 > 编程语言 > Java开发

Leetcode刷题记—— Remove Duplicates from Sorted Array II(已排序数组移除重复元素2)

2017-03-04 17:48 741 查看
一、题目叙述:

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.

Subscribe to see which companies asked this question.

排序数组中一个元素最多只能重复2次,将多余的移除

二、解题思路:

Medium题。

思路:

(1)倒着遍历数组,若当前元素与其前前一个元素的值不同,计数加1;否则,将后续元素前移。

(2)注意当数组元素小于等于2的情况。

三、源码:

import java.util.Arrays;

public class Solution
{
public int removeDuplicates(int[] nums)
{
if (nums.length <= 2) return nums.length;
int count = 2;
for (int i = nums.length - 1; i >= 2; i--)
{
if (nums[i] != nums[i - 2])
count ++;
else
for (int j = i; j < nums.length - 1; j ++)
nums[j] = nums[j + 1];
}
System.out.println(Arrays.toString(nums));
return count;

}

public static void main(String args[])
{

Solution solution = new Solution();
int[] nums = {1, 1, 1, 2, 2, 3};
System.out.println(solution.removeDuplicates(nums));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode
相关文章推荐