赞
踩
https://leetcode.com/problems/single-number/description/
Given a non-empty 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?
Example1:
Input: [2,2,1]
Output: 1
Example2:
Input: [4,1,2,1,2]
Output: 4
给定一个一维数组,数组中的每个数都会出现两次,但是只有一个数会出现一次,找出这个出现一次的数。
因为每个数都会出现两次,所以要记录出现的数和对应的这个数出现的次数,因此想到使用hashMap来存储。键用来存储数,值用来存储数对应的出现的次数。
class Solution {
public int singleNumber(int[] nums) {
int ret = 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int n: nums) {
if(map.containsKey(n)){
map.put(n, map.get(n) + 1);
}else{
map.put(n, 1);
}
}
for(int r: map.keySet()) {
if(map.get(r) == 1)
return r;
}
return ret;
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。