1 题目描述
1.1 英文描述
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Input: nums = [1]
Output: 1
1.2 中文描述
给你一个非空的整数数组,这个数组中有一个整数只出现了一次,其它的整数都出现两次,你要找出这个只出现一次的整数。
比如说,给你的数组是:
5, 7, 5, 6, 6
这里 7 只出现了一次,因此你要返回的就是 7。
2 解法
2.1 解法1 - 使用set解决
//方式1:使用set解决
public static int singleNumber(int[] nums){
Set<Integer> set = new TreeSet<>();
for(int num : nums){
if(set.contains(num)){
set.remove(num);
}else {
set.add(num);
}
}
return ((TreeSet<Integer>) set).first();
}
2.2 解法2 - 位运算
//方式2:位运算
public static int singleNumber2(int[] nums){
int res = 0;
for(int num : nums){
res ^= num;
}
return res;
}