[LeetCode] - Single Number

来源:互联网 发布:免费域名com申请 编辑:程序博客网 时间:2024/06/16 10:53

Description: 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?

这是整个LeetCode上面做的第一道题。没啥好说的,XOR即可。

public class Solution {    public int singleNumber(int[] A) {        int single = 0;        for(int i=0; i < A.length; i++) {            single ^= A[i];        }        return single;    }}


http://stackoverflow.com/questions/1089987/given-an-array-of-numbers-except-for-one-number-all-the-others-occur-twice-gi

Assuming you can XOR the numbers, that is the key here, I believe, because of the following properties:

  • XOR is commutative and associative (so the order in which it's done is irrelevant).
  • a number XORed with itself will always be zero.
  • zero XORed with a number will be that number.

So, if you simply XOR all the values together, all of the ones that occur twice will cancel each other out (giving 0) and the one remaining number (n) will XOR with that result (0) to give n.

0 0
原创粉丝点击