LeetCode - 80. Remove Duplicates from Sorted Array II
来源:互联网 发布:js文件在线格式化 编辑:程序博客网 时间:2024/05/18 02:58
方法一:
这一种方法是第一个想到的,因为题目中要求删除的是出现两次及其以上的元素,所以在思考的时候想到了使用HashMap来记录数组中每个元素出现的次数,对于出现次数大于2的元素就删除。删除的方法是由26. Remove Duplicates from Sorted Array的思路得来,使用两个指针,碰到重复>=两次的直接跳过,其余的向前移动的前一个指针指定的位置上
/* HashMap */public class Solution { public int removeDuplicates(int[] nums) { //extreme situation if(nums == null) return 0; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); //init HashMap for(int i = 0; i < nums.length; i++){ if(map.containsKey(nums[i])){ map.replace(nums[i], map.get(nums[i]) + 1); }else{ map.put(nums[i], 1); } } int index = 0; for(int i = 1; i < nums.length; i++){ if(map.get(nums[i]) <= 2){ index++; nums[index] = nums[i]; }else{ //update HashMap map.replace(nums[i], map.get(nums[i]) - 1); } } return index + 1; }}
方法二:
方法一确实可以解决这个问题,但是这却忽略了题目中的一个非常重要的条件:sorted,所以方法一是通用的,无论对于排序过的还是没有排序的都可以使用。sorted这个条件说明了一个问题,那就是与某元素相同的元素只可能在它的周围。在删除数组中的重复元素时,我们需要比较的是某元素和index - 2位置的元素的大小,在这种方法中,如果遇到的元素并不是重复了>=2次,那么index就会与i一直保持同步并在每一次循环中+1,如果遇到的是重复多次的元素的前两次出现时也是如此,只有当第三次出现的时候,i和index - 2位置上的元素才会相等,此时i开始跳过并寻找下一个不想等的元素。这种方法是一个通用的方法,以后如果要删除重复n次的元素,也只要在这种方法上进行微调即可
/* Element Compare */public class Solution { public int removeDuplicates(int[] nums) { //extreme situation if(nums == null) return 0; if(nums.length < 2) return nums.length; int index = 2; for(int i = 2; i < nums.length; i++){ if(nums[i] != nums[index - 2]){ nums[index] = nums[i]; index++; } } return index; }}知识点:
1. HashMap: get(key), put(key, value), replace(key, newValue);
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
- Harbor Registry项目源代码结构解析
- 安卓网站收集
- Bshare分享
- SQL Server简洁分页代码
- 集合之LinkedHashSet
- LeetCode - 80. Remove Duplicates from Sorted Array II
- 如何标准化特征向量HOW TO NORMALISE FEATURE VECTORS
- 表达式树
- Android Studio的相关设置信息笔记
- Frament与activity切换
- [REDIS]: Codis作者黄东旭细说分布式Redis架构设计和踩过的那些坑
- Java注解不为人知的作用
- HashSet---Contains Duplicate
- 试用阿里云RDS的MySQL压缩存储引擎TokuDB