leetcode-136. Single Number

来源:互联网 发布:淘宝网手套 编辑:程序博客网 时间:2024/04/30 19:19

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?

思路:遍历异或,最后剩下的就是唯一的那个数

class Solution {public:    int singleNumber(vector<int>& nums) {        //依次遍历异或,最后剩的就是唯一的那个值        //扩展:如果有两个不同的,异或完后看结果的哪一个bit为1,        //选一个,根据这个bit为1和0把数组分成两组,分别遍历异或得到两个不同值        int length = nums.size();        if(length == 0)        {            return 0;        }        int result = nums[0];        for(int i = 1;i < length;i++)        {            result = result^nums[i];        }        return result;    }};
0 0
原创粉丝点击