leetcode题解-80. Remove Duplicates from Sorted Array II
来源:互联网 发布:oracle 数据库日志 编辑:程序博客网 时间:2024/06/05 04:29
题目:
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以内即可,使用一个标志来标识。首先想到的最简单的思路应该是使用map来标记每个数的出现次数,大于2时不再进行操作,2以内的则对数组相应元素进行赋值。代码入下:
public int removeDuplicates(int[] nums) { int count = 0; Map<Integer, Integer> map = new HashMap<>(); for(int i=0; i<nums.length; i++){ if(!map.containsKey(nums[i])) { nums[count] = nums[i]; map.put(nums[i], 1); count++; }else if(map.get(nums[i]) == 1) { nums[count] = nums[i]; map.put(nums[i], map.get(nums[i]) + 1); count++; } } return count; }
这种方法因为使用了hashmap导致算法效率较低,我们考虑能不能仅使用一个标记来依次表示所有数字出现次数,就有了下面的代码,使用一个boolean型的flag标志前后相邻数字是否相等:
public static int removeDuplicates1(int[] nums){ if(nums.length<=1) return nums.length; int count = 1; boolean flag = false; for(int i=1; i<nums.length; i++){ if(nums[i] == nums[i-1] && !flag){ nums[count] = nums[i]; count++; flag = true; }else if(nums[i] != nums[i-1]){ nums[count] = nums[i]; count++; flag = false; } } return count; }
另外,在discuss中看到了一种极其简洁的代码,如下所示,很6:
public int removeDuplicates2(int[] nums) { int i = 0; for (int n : nums) if (i < 2 || n > nums[i-2]) nums[i++] = n; return i; }
0 0
- leetcode题解-80. Remove Duplicates from Sorted Array II
- LeetCode题解:Remove Duplicates from Sorted Array I and II
- LeetCode 题解(162): Remove Duplicates from Sorted Array II
- leetcode题解-80 Remove Duplicates from Sorted Array II
- LeetCode题解:Remove Duplicates from Sorted Array
- [LeetCode]Remove Duplicates from Sorted Array题解
- 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
- MindManager思维导图——物理教学应用
- OOZIE系统成功在hadoop-2.7.3版本…
- java自己造 编程IDE【2】,消…
- java自己造 编程IDE【3】,对…
- 【汇总】ExitCodeException问题Ooz…
- leetcode题解-80. Remove Duplicates from Sorted Array II
- Oozie运行python的spark job…
- Oozie报错Py4JJavaError Secu…
- OOZIE系统成功【2】跑通定时调度的…
- iOS逆向工程之App脱壳
- Oozie 4.3.0运行Error: …
- 构造版本一直无法出来
- Oozie报错ClassNotFoundException:…
- nginx服务器搭建及部署