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?

这个主要考虑的是位运算中的异或操作符,根据a^b = b^a,  a^a =0, 0^a = a,对所有的数进行异或,最后就可以得到只出现1次的数字

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


你可能感兴趣的:(LeetCode)