【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次以上的元素。
思路:复制数组,并与原数组对比,
思路2:遍历数组,建立不含过度重复元素子数组的指针,把与前两位不同的数取代指针位即可。
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-80]Remove Duplicates from Sorted Array II(C)
- leetcode-26&80 Remove Duplicates from Sorted Array I&II
- [LeetCode 80]Remove Duplicates from Sorted Array II
- leetcode80 Remove Duplicates from Sorted Array II
- [C语言][LeetCode][80]Remove Duplicates from Sorted Array II
- 【LEETCODE】80-Remove Duplicates from Sorted Array II [Python]
- leetcode80 Remove Duplicates from Sorted Array II
- LeetCode80 Remove Duplicates from Sorted Array II
- LeetCode 26, 80, 81, 82, . Remove Duplicates from Sorted Array/ List i, ii
- (java)leetcode-80:Remove Duplicates from Sorted Array II
- Leetcode 80 Remove Duplicates from Sorted Array II
- 【leetcode c++】80 Remove Duplicates from Sorted Array II
- LeetCode(80) Remove Duplicates from Sorted Array II
- leetcode题解-80 Remove Duplicates from Sorted Array II
- LeetCode 80 Remove Duplicates from Sorted Array II(移除数组中出现两次以上的元素)
- [leetcode 80] Remove Duplicates from Sorted Array II
- [Leetcode 30] 80 Remove Duplicates From Sorted Array II
- LeetCode 80: Remove Duplicates from Sorted Array II
- LeetCode(80) Remove Duplicates From Sorted Array II
- Leetcode: 80. Remove Duplicates from Sorted Array II