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?

  这道题目的时间复杂度必须是O(n),并且空间复杂度为O(1),使得不能用排序方法,也不能使用map数据结构。那么只能另辟蹊径,需要用位操作Bit Operation来解此题。

  这里用到逻辑异或的两个性质:

  一:相同的两个int型数据 ^ 之后为0

  二:逻辑异或满足交换律、结合律,即对于题目中的数组可以看成是先把元素排好序相同的放在一块进行异或运算,与元素的参加运算的顺序无关。

  逻辑异或的运算真值表:

输入
运算符
输入
结果
1
0
1
1
1
0
0
0
0
0
1
1

 代码:

public class Solution {
    public int singleNumber(int[] nums) {
        int ans = 0;
        for(int n:nums){
            ans ^= n;
        }
        return ans;
    }
}
原文地址:https://www.cnblogs.com/mxk-star/p/7291703.html