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?
这个题用位操作中的亦或:
a^a=0,a^0=a,a^b^b=a
public class Solution {
public int singleNumber(int[] nums) {
int res = nums[0];
for (int i = 1; i < nums.length; ++i) res ^= nums[i];
return res;
}
}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?
建立一个32位的数字,来统计每一位上1出现的个数,我们知道如果某一位上为1的话,那么如果该整数出现了三次,对3去余为0,我们把每个数的对应位都加起来对3取余,最终剩下来的那个数就是单独的数字。
public int singleNumber(int[] nums) {
int res = 0;
for (int i = 0; i < 32; ++i) {
int sum = 0;
for (int j = 0; j < nums.length; ++j) {
sum += (nums[j] >> i) & 1;
}
res |= (sum % 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?
首先计算nums数组中所有数字的异或,记为xor
令lowbit = xor & -xor,lowbit的含义为xor从低位向高位,第一个非0位所对应的数字
例如假设xor = 6(二进制:0110),则-xor为(二进制:1010,-6的补码,two's complement)
则lowbit = 2(二进制:0010)
根据异或运算的性质,“同0异1”
记只出现一次的两个数字分别为a与b
可知a & lowbit与b & lowbit的结果一定不同
通过这种方式,即可将a与b拆分开来
public class Solution {
public int[] singleNumber(int[] nums) {
int[] res = new int[2];
int result = nums[0];
for(int i=1;i<nums.length;i++){
result = result^nums[i];
}
res[0] = 0;
res[1] = 0;
int n = result & (~(result-1));
for(int i=0;i<nums.length;i++){
if((n & nums[i])!=0){
res[0] = res[0] ^ nums[i];
}else {
res[1] = res[1] ^ nums[i];
}
}
return res;
}
}
寻找唯一元素
本文介绍三种算法,用于在数组中找到仅出现一次的元素。SingleNumber使用异或解决两次重复问题;SingleNumberII介绍如何在线性时间和常数空间复杂度内找出三次重复中的独特值;SingleNumberIII提供了解决两个唯一元素的方案。
683

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



