题目原址
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来存储。键用来存储数,值用来存储数对应的出现的次数。
- 通过for循环来遍历整个数组,如果这个数没有出现过,则将其添加到map中,将值置为1
- 如果出现过,则获取这个数的值再+1,其实可以不获取值直接将值置为2。因为题中说一个数只能出现1次或2次
- 最后遍历集合,找到集合中值为1的键,返回即可。
AC代码
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;
}
}