Expected:linear runtime complexity, constant space complexity.(像当初的我直接用关联容器暴力解决…)
Single Number I
Given an array of integers, every element appears twice except for one. Find that single one.
public class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for(int i=0;i<nums.length;i++)
result = result ^ nums[i];
return result;
}
}
//只有这道完全是自己想到的...因为想到一种用位操作实现两数互换的方法(不需要用temp):
// A = A^B;
// B = A^B;
// A = A^B;
Single Number II
Given an array of integers, every element appears three times except for one. Find that single one.
//方法一(Single Number I也可以用)
//统计数组中的数字每一位上'1'的个数,对3取余即可得到SingleNumber在该位是'0'还是'1'
public class Solution {
public int singleNumber(int[] nums) {
int temp;
int result = 0;
for(int i=0;i<32;i++){
temp = 0;
for(int j=0;j<nums.length;j++){
temp += (nums[j]>>i)&1;
}
temp %= 3;
result |= (temp<<i);
}
return result;
}
}
//方法二:amazing...
public class Solution {
public int singleNumber(int[] nums) {
int one=0;
int two=0;
int i,j,k;
//其中的one代表目前为止number出现了一次
//two代表出现了两次
//three代表出现了三次
for(i=0; i<nums.length; i++)
{
two = two |(one&nums[i]);//当one为'1'时,two为'1'(已经出现过一次,现在又出现一次),当one为‘0’时,two不变
one = one^nums[i];//出现了奇数次则为非0
int three = two&one;
two = two^three; //当one和two都达到非零时,用three将two置零
one = one^three; //用three将one置零
}
return one|two;
}
}
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].
public class Solution {
public int[] singleNumber(int[] nums) {
int attempt = 0;
for(int i=0;i<nums.length;i++){
attempt ^= nums[i];//得到两个结果的异或
}
//如何把二者分离?
//找到异或结果中某位为'1'的位置,然后将原数组中此位为'1'的分为一类,为'0'的分为一类
//为了计算考虑,通常寻找最后一个'1'的位置,而且有一个很巧妙的公式:
int lastOne = attempt & (~(attempt-1));
int a = 0;
int b = 0;
for(int i=0;i<nums.length;i++){
if( (nums[i]&lastOne) == 0) a^=nums[i];
else b^=nums[i];
}
int[] result = new int[2];
result[0] = a;
result[1] = b;
return result;
}
}