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;
    }
};
全部评论

相关推荐

joe2333:怀念以前大家拿华为当保底的日子
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务