leetcode 80. Remove Duplicates from Sorted Array II
来源:互联网 发布:淘宝店铺封了怎么解封 编辑:程序博客网 时间:2024/05/22 12:25
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.
这道题题意很明了,我这里使用的是遍历解法,可以得到目标数组,这道题的麻烦的地方就是得到目标数组。假如不考虑这点的话,使用HashMap遍历一次,然后就可以得到结果了。
代码如下;
public class Solution{ /* * 这个问题的难点主要在于要在原数组的基础上得到目标数组, * 本题并不难 * */ public int removeDuplicates(int[] nums) { if(nums==null || nums.length<=2) return nums.length; int count=2,start=2,end=nums.length; while(start < end) { if(nums[start-2]==nums[start-1]) { if(nums[start]!=nums[start-1]) { count++; start++; } else { //这个问题的难点主要在于要在原数组的基础上得到目标数组, for(int j=start+1;j<end;j++) nums[j-1]=nums[j]; nums[end-1]=nums[start]; end--; } }else { count++; start++; } } return count; }}
下面是C++的做法,就是遍历一次,其实我更倾向于使用map来做计数
代码如下:
#include <iostream>#include <vector>using namespace std;class Solution {public: int removeDuplicates(vector<int>& nums) { if (nums.size() <= 2) return nums.size(); int count = 2; int begin = 2, end = nums.size(); while (begin < end) { if (nums[begin - 2] == nums[begin - 1]) { if (nums[begin - 1] == nums[begin]) { for (int i = begin + 1; i < end; i++) nums[i - 1] = nums[i]; nums[end - 1] = nums[begin]; end--; } else { count++; begin++; } } else { count++; begin++; } } return count; }};
阅读全文
0 0
- leetcode——26. Remove Duplicates from Sorted Array && 80. Remove Duplicates from Sorted Array II
- LeetCode 26. Remove Duplicates from Sorted Array && 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
- 线程与进程的概念和区别
- 【模板】倍增法求lca
- Git仓库SSH Key 的配置
- 数据结构 循环链表
- POJ 3600 Subimage Recognition(dfs)
- leetcode 80. Remove Duplicates from Sorted Array II
- TensorFlow在MNIST数据集上实现神经网络
- Java编程规范
- jdk源码二 Object对象你懂了吗?
- 二叉树寻找最近公共祖先
- 幂等性理解和解决方案
- Java transient关键字使用小记
- Activiti选人页面的实现
- 圆周长面积计算