您的位置:首页 > 编程语言 > C#

【LeetCode】C# 80、Remove Duplicates from Sorted Array II

2017-10-16 10:09 417 查看
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.

给定有序数组。取出重复2次以上的元素。

思路:复制数组,并与原数组对比,
temp[i]!=temp[i-2]
判断是否重复3次,否则往原数组中刷新该位数值。

public class Solution {
public int RemoveDuplicates(int[] nums) {
if(nums.Length<=2)return nums.Length;
int[] temp = new int[nums.Length];
for(int i = 0; i < nums.Length; i++)
{
temp[i] = nums[i];
}
int sum=2;
for(int i=2;i<nums.Length;i++){
if(temp[i]!=temp[i-2]) {
nums[sum]=nums[i];
sum++;
}
}
return sum;
}
}


思路2:遍历数组,建立不含过度重复元素子数组的指针,把与前两位不同的数取代指针位即可。

public class Solution {
public int RemoveDuplicates(int[] nums) {
int i = 0;
foreach (int n in nums)
if (i < 2 || n > nums[i-2])
nums[i++] = n;
return i;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c#