您的位置:首页 > 编程语言 > Java开发

leetcode解题之136 #Single Number Java版(只出现一次的数字)

2017-03-14 13:24 381 查看

136. Single Number

Given an array of integers, every element appearstwice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

只出现一次的数字,其他全部两次,能不使用额外的空间吗?
使用map:

public  int singleNumber(int[] nums) {
int i = 0;
int j = nums.length - 1;
Map<Integer, Integer> map = new HashMap<>();
while (i <= j) {
if (map.containsKey(nums[i]))
map.put(nums[i], map.get(nums[i])+1);
else
map.put(nums[i], 1);
i++;

}
i = 0;
while (i <= j) {
if (map.get(nums[i]) == 1)
break;
i++;
}
return nums[i];
}


使用异或运算:

如果a、b两个值不相同,则异或结果为1。如果a、b两个值相同,异或结果为0。

0与任何数做异或都是 那个数,相同的数字做异或等于0;

    1. a ^ b = b ^ a

    2. a ^ b ^ c = a ^ (b ^ c) = (a ^ b) ^ c;

public  int singleNumber(int[] nums) {

int result = nums[0];

for (int i = 1; i < nums.length; i++) {
result = result ^ nums[i];
}

return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐