[LeetCode]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?

给你一个数组,数组中除了一个元素出现过一次,其他的均出现两次,找到那个只出现过一次的元素。(需要线性复杂度,最好不使用额外的空间)。

解题思路

相同的两个数异或(^)为0,将所有的数进行异或则仅剩下那个单独的元素。

代码

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



你可能感兴趣的:([LeetCode]Single Number)