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

来源:互联网 发布:sublime 格式化js css 编辑:程序博客网 时间:2024/05/20 09:44

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;    }}
阅读全文
0 0
原创粉丝点击