您的位置:首页 > 其它

Leetcode题解14 136. Single Number

2016-04-19 10:07 495 查看
Given an array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

很显然,这个解法不是最好的方式,留个坑,以后继续。

public static int singleNumber(int[] nums) {
HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
int temp;
for (int i = 0; i < nums.length; i++) {
if (hashMap.get(nums[i]) != null) {
temp = hashMap.get(nums[i]);
hashMap.put(nums[i], ++temp);
} else {
hashMap.put(nums[i], 1);
}
}
Iterator it = hashMap.keySet().iterator();
while (it.hasNext()) {
int key = (int) it.next();
for (int i = 0; i < hashMap.get(key); i++) {
if (hashMap.get(key) == 1) {
return key;
}
}
}
return -1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode