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?
解法一:Language-Java Time-O(n) Space-O(1) Run Time-7ms
把每个整数按位相加,每一位%3,得到的二进制串变为整数就是要求的数,这个方法可以解决这一类问题,比如every element appears two times except for one…
public class Solution {
public int singleNumber(int[] nums) {
int[] arr = new int[32];
int res = 0;
for(int i = 0, right = 0; i < 32 ; i ++, right ++)
{
for(int j = 0; j < nums.length; j ++ )
{
arr[i] += nums[j] >> right & 1;
}
arr[i] %= 3;
}
for(int i = 0, left = 0; i < 32; i ++, left ++ )
{
res += arr[i] << left;
}
return res;
}
}
下面是进行优化了的代码,可以忽略上面的代码直接看以下代码,优化后Run Time-3ms
public class Solution {
public int singleNumber(int[] nums) {
int[] arr = new int[32];
int res = 0;
for(int i = 0; i < 32 ; i ++)
{
for(int j = 0; j < nums.length; j ++ )
{
arr[i] += nums[j] >> i & 1;
}
arr[i] %= 3;
res += arr[i] << i;
}
return res;
}
}
解法二:Language-Java Time-O(n) Space-O(n) Run Time-18ms
public class Solution {
public int singleNumber(int[] nums) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int res = 0;
for(int i = 0 ; i < nums.length; i ++)
{
if(!map.containsKey(nums[i]))
{
map.put(nums[i], 1);
}else
{
map.put(nums[i], map.get(nums[i]) + 1);
//如果出现3次就删除,最后map中剩余的那个元素就是要求的Single Number,这样可以使Run Time减少7ms
if(map.get(nums[i]) == 3)
{
map.remove(nums[i]);
}
}
}
for(int n : map.keySet())
{
if(map.get(n) == 1)
{
res = n;
}
}
return res;
}
}