【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
- 【LeetCode】C# 80、Remove Duplicates from Sorted Array II
- LeetCode-Array-80 Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array II
- [leetcode]Remove Duplicates from Sorted Array II
- LeetCode-Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- LeetCode - Remove Duplicates from Sorted Array II
- LeetCode:Remove Duplicates from Sorted Array II
- LeetCode | Remove Duplicates from Sorted Array II
- Leetcode: Remove Duplicates from Sorted Array II
- 【leetcode】Remove Duplicates from Sorted Array II
- Leetcode: Remove Duplicates from Sorted Array II
- Android-25种开源炫酷动画框架
- equals()方法总结
- 【bzoj1190】[HNOI2007]梦幻岛宝珠 分层背包dp
- 快速排序
- 剑指 03-—链表从尾到头打印
- 【LeetCode】C# 80、Remove Duplicates from Sorted Array II
- Android自定义对话框
- phpstorm 2017激活
- centos 打开配置文件出错:E325: ATTENTION Found a swap file by the name "/etc/vsftpd/.vsftpd.conf.swp"
- Spring RestTemplate作为负载平衡器客户端
- ABAP 动态生成内表的几种方法(Several Methods of Dynamic Internal Table Creation)
- 虚拟数字货币开发小专家薪捷讲述,关于虚拟数字货币之王比特币论文区块链挖矿原理的那些事儿
- MVC使用Newtonsoft无需实体类,实现JSON数据返回给前端页面使用
- mysql触发器创建、查看、删除语法