[LeetCode] 136. Single Number(位操作)

传送门

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?

思路

题意:给定一个数组,其中只有一个数没有出现两次,要求时间复杂度为线性且空间复杂度为O(1)找出这个数。

题解:因为题目只有一个数出现一次,其他数出现两次,因此很容易想到用异或运算符来求解,主要是以前做过类似的题,不然应该也挺难想到要用异或运算符吧

 
 
C++:
class Solution {
public:
    //13ms
    int singleNumber(vector<int>& nums) {
        int res = 0;
        for (unsigned i = 0;i < nums.size();i++){
            res ^= nums[i];
        }
        return res;
    }
};

 

Java:

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

你可能感兴趣的:([LeetCode] 136. Single Number(位操作))