Remove Duplicates from Sorted Array II
来源:互联网 发布:java 二维码 编辑:程序博客网 时间:2024/06/05 03:11
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3]
,
Your function should return length = 5
, and A is now [1,1,2,2,3]
.
“删除重复元素”的延续:
如果重复被允许至多两次又怎样呢?
例如:
给定排序了的数组 A = [1,1,1,2,2,3]
,
你的函数应该返回长度 s ,并且现在的A 是 [1,1,2,2,3]
.
此题想到了用哈希来做,但是发现Java中的HashMap不支持按照读入顺序读出,于是使用LinkedHashMap。
Java:
public int removeDuplicates(int[] A) {LinkedHashMap<Integer,Integer> map = new LinkedHashMap<Integer,Integer>();for (int i = 0; i < A.length; i++) {//对元素的出现次数做记录if (map.containsKey(A[i]))map.put(A[i], map.get(A[i]) + 1);elsemap.put(A[i], 1);}int sum=0;//计算最后数组需要的长度for (Map.Entry<Integer,Integer> m : map.entrySet()){if(m.getValue() >2)sum += 2;elsesum += m.getValue();}int i=0;//对新数组赋值for (Map.Entry<Integer,Integer> m : map.entrySet()){if(m.getValue() > 1){ int temp = A[i++] = m.getKey();A[i] = temp;}else{A[i] = m.getKey();}i++;}return sum; }
0 0
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- Remove duplicates from sorted array II
- Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- [leetcode]Remove Duplicates from Sorted Array II
- LeetCode-Remove Duplicates from Sorted Array II
- centos使用yum安装libpcap
- Android APP 分享图片文字到微信刚开始正常,后面就不弹出分享框了
- 用 UrlRewriteFilter 实现 URL 重写
- Dalvik虚拟机
- 伪分布式Hadoop配置安装
- Remove Duplicates from Sorted Array II
- openssl windows 编译
- QQ手机精灵 http://www.apkbus.com/blog-33641-44366.html
- Swift 初见
- 空间射线与三角面相交算法及实现
- 增强for循环用法
- Android源代码涉及的设计模式,持续更新
- 【Android核心基础02】 - 界面布局、测试、数据存储访问、权限控制、XML
- Linux内核同步机制之completion