136. Single Number

来源:互联网 发布:城口综合数据库中标 编辑:程序博客网 时间:2024/06/06 18:13

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?

Subscribe to see which companies asked this question

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

解释:当使用异或,无论本来是1 还是 0 ,当遇到偶数个1或者偶数个0,那么那些偶数个1或者偶数个0都会自己对消,无论这些偶数个1,0使用异或操作的先后顺序如何。

0 0
原创粉丝点击