LeetCode 136. 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?

Subscribe to see which companies asked this question.

【题目分析】

给定一个整数数组,数组中的元素都正好出现两次,除了其中一个元素。找出这个元素。

【思路】

这是一个位运算的题目。在位运算中,异或运算有这样的性质,一个数与同一个数异或两次,无论顺序如何,都会得到这个数本身。在这个题目中由于其他元素都正好出现两次,当把所有的元素异或到一起的话,这些元素正好都被消除,最后的结果就是正好出现一次的那个元素。

如果考虑元素的每一位的话,如果偶数个1异或,最后的结果位0。

【java代码】

public class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        for(int i : nums) {
            result = result ^ i;
        }
        return result;
    }
}

 

posted @ 2017-02-25 20:56  Black_Knight  阅读(119)  评论(0编辑  收藏  举报