您的位置:首页 > 其它

136. Single Number

2016-05-31 10:19 253 查看
题目:

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?

题意:
给定一个整数数组,除了其中一个元素只出现一次之外,其他每一个元素都出现两次。

note:

算法要求不使用额外的空间实现线性时间复杂度。

思路一:

直接轮训数组,将数组的每个元素做异或操作,结果即为single number。

代码:20ms

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        
        int result = nums[0];
        for(int i=1; i<nums.size(); i++){
            result ^= nums[i];
        }
        
        return result;
    }
};代码:20ms
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        
        for(int i=1; i<nums.size(); i++){
            nums[0] ^= nums[i];
        }
        
        return nums[0];
    }
};
代码:20ms
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        
        return nums.size() == 0 ? 0 : accumulate(nums.begin(), nums.end(), 0, bit_xor<int>());
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: