Single Number Ⅰ:
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 class Solution {
public int singleNumber(int[] nums) {
if(nums.length == 1){
return nums[0];
}
for(int i = 1; i < nums.length; i++){
nums[0] = nums[0] ^ nums[i];
}
return nums[0];
}
}
代码:
public class Solution {
public int singleNumber(int[] nums) {
HashSet<Integer> set = new HashSet<Integer>();
for(int n : nums){
if(!set.add(n)){
set.remove(n);
}
}
Iterator<Integer> it = set.iterator();
return it.next();
}
}Single Number II:
Given an array of integers, every element appears three times 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 class Solution {
public int singleNumber(int[] nums) {
int [] numsOfBits = new int[32];
int res = 0;
for(int i = 0; i < 32; i++){
for(int j = 0; j <nums.length; j++){
numsOfBits[i] += (nums[j] >> i) & 1;
}
res |= (numsOfBits[i] % 3) << i;
}
return res;
}
}Single Number III:
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].
Note:
- The order of the result is not important. So in the above example,
[5, 3]is also correct. - Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
分析:本题要求线性复杂度,位运算是首先要想到的。与题目一不同,本题有两个数出现一次,那么找到两个数的不同是关键。由题目一的启发,异或可以得到两个数字存在的不同位,利用两个数字在某一位的差别,可以将数组分成两部分分别用题目一的方法来求得两个数:
代码:
public class Solution {
public int[] singleNumber(int[] nums) {
int result[] = {0,0};
int temp = nums[0];
for(int i = 1; i < nums.length; i++){
temp = temp ^ nums[i];
}
int difference = temp & (~(temp - 1));
for(int i = 0; i < nums.length; i++){
if((difference & nums[i]) == 0){
result[0] = result[0] ^ nums[i];
}else{
result[1] = result[1] ^ nums[i];
}
}
return result;
}
}int difference = temp & (~(temp - 1));这条语句表示取出两个数最小的不同位用来分割数组。
本文介绍三种算法,通过位运算解决数组中寻找唯一出现一次的元素问题。包括:寻找仅出现一次的元素、每种元素出现三次但一种只出现一次、两种元素各出现一次而其余均出现两次的情况。

被折叠的 条评论
为什么被折叠?



