LeetCode: 136. Single Number

LeetCode: 136. Single Number

题目描述

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

解题思路

直接全部数字按位异或, 两个相同的数字一定会抵消掉,最后剩下的就是单独的那个数、

AC代码

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

        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/yanglingwell/article/details/80865369