LeetCode--No.136--Single Number

来源:互联网 发布:邪恶漫画网站源码免费 编辑:程序博客网 时间:2024/05/30 23:27

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?

这个用hash的话,时间O(n)是没问题的,但是空间也会变成O(n)。
下面的解法我拍一天脑袋,估计也拍不出来=。=

-----

1. 异或

0^0 = 0, 1^1 = 0, 1^0 = 1, 0^1 = 1;
也就是说,同样的数字抑或后为0,不同的数字异或后为1.
当我们有integers数组,a,a,b,b,c时,a与a异或后为0,b与b异或后为0,即aabb异或后为0.下面考虑0与c进行异或。
考虑每一位,0与0异或后的结果为0,也就是保持0不变,0与1异或后结果为1,保持1不变。所以Int 0 与另一位int异或后的结果,是保持这个数不变的。

2. 所以对于这道题来说,我们可以将数组中所有的数异或一下。最后的结果即为所求数字。

代码如下:

public class Solution {    public int singleNumber(int[] nums) {        if(nums.length == 0)            return 0;        else if (nums.length > 1){            for(int i = 1; i < nums.length; i++){                nums[0] = nums[0] ^ nums[i];            }        }        return nums[0];    }}


0 0
原创粉丝点击