【Leetcode】136. Single Number(求解只出现一次的数)(异或)(2019年美团无人驾驶算法实习面试原题)

版权声明:本文为博主原创文章,未经博主许可允许转载。 https://blog.csdn.net/qq_29600137/article/details/89761944

Given a non-empty 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?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4

题目大意:

给出一个数组其中只有一个数是出现一次的,其余的数都是出现两次,请找出这个数。

解题思路:

首先我们要了解异或运算,"^"。其表示的是二进制的逐位运算,eg:

3^3 = 0 即11^11=00,表示如果当前位置数据相同则为0,如果不同则为1。

那我们可以理解成如果在数组当中相同的数字互相抵消,最后只留下独立的那一个即可。

class Solution {
public:
    int singleNumber(vector<int>& nums) {
         
        int ans = nums[0];
        for(int i=1;i<nums.size();i++){
            ans = ans^nums[i];
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_29600137/article/details/89761944