260. Single Number III
来源:互联网 发布:普通话标准发音软件 编辑:程序博客网 时间:2024/06/06 02:22
Given an array of numbers nums
, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5]
, return [3, 5]
.
题意:数组中只有2个元素只出现了1次,其他元素都出现了2次,请找出这2个元素。
自然联想到使用HashMap,元素值作为Key,出现的次数作为Value,只要找到Value为1的key就好了。
下面贴代码:
public class Solution { public int[] singleNumber(int[] nums) { int[] a1 = new int[2]; int k = 0; HashMap<Integer,Integer> h = new HashMap<>(); for(int a : nums){ if(h.containsKey(a)){ //若已存在,value加1 h.put(a,h.get(a)+1); }else{ //若不存在,添加 h.put(a,1); } } for(Map.Entry m:h.entrySet()){ //遍历hashmap中的键值对 if((int)m.getValue()==1){ a1[k++] = (int)m.getKey(); } } return a1; }}解法中使key存在的value加1的语句为 h.put(a,h.get(a)+1);如果大家有更好的可以在下方留言,非常感谢。
另外遍历hashmap中的键值对使用的是entrySet()方法,我们看一下API中该方法:
返回的是一个Set,元素类型是Map.Entry。其中,Entey是hashmap中的一个静态内部类,用来存放键值对的,在Entry中的我们可以使用getValue和getKey方法来取得键值对中的值和键。
阅读全文
0 0
- 260.Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 260. Single Number III
- 三星Galaxy S8打开USB调试
- vue项目使用手机浏览器访问时报错:Uncaught TypeError: Object.assign is not a function
- 关于python的urllib的一些简单明了的介绍
- USACO-Section1.3 Mixing Milk [贪心]
- 回归分析资料
- 260. Single Number III
- Deeplearning4j 实战(8) : Keras为媒介导入Tensorflow/Theano等其他深度学习库的模型
- 基于JAINSIP协议栈的一个简单SIP服务器实现流程
- vue(1) -- this.$nextTick
- Matlab 相关函数说明
- 当我真正搞懂主席树!!!
- 电路交换和分组交换
- 剑指offer 面试题42 翻转单词顺序 VS 左旋转字符串
- 把"Essential C++"读薄(一)