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

相关推荐

爱睡觉的冰箱哥:学历不够啊兄弟,分析师都是9硕✌🏻咱搞不过他们滴
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-11 11:22
怎么这么多逆天求职者,救救我救救我救救我😭
flmz_Kk:哈哈哈哈哈哈,这么多求职者,肯定有那一两个逆天的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务