260 Single Number III

原题描述

Single Number III
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

分析

与之前那题类似,只不过这次数组中出现一次的数字有两个,要求线性复杂度,还是考虑利用map的查找算法。

代码示例

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        map<int, int> record;
        vector<int> result;
        for (vector<int>::iterator i = nums.begin(); i != nums.end(); ++i)
        {
            if (record.find(*i) == record.end())
                record[*i] = 1;
            else
                record[*i] += 1;
        }
        for (map<int, int>::iterator i = record.begin(); i != record.end(); ++i)
        {
            if (i->second == 1)
                result.push_back(i->first);
        }
        return result;
    }
};

改进

与之前那题一样,运行时间不太理想。题目中给出的提示有位运算,考虑由此改进程序。
使用位运算的时候具体做法跟题目有关。
对于之前的Single Number,出现1次的数字只有一个,则将数组元素从第一个到最后一个不断异或,由于出现两次的数字之间异或会得到零,则最后的结果便是只出现一次的那个数字。
对于本题,出现一次的数字有两个,所以考虑将数组分为两部分,每部分含一个出现一次的数字。
1.将所有数字依次异或,则得到的结果是两个出现一次数字的异或值
2.将结果转换为二进制,找一个为1的位
3.将数组中元素按该位是否为1分为两部分,则可以保证将两个数字分开
4.分别将两部分中的数字依次异或,得到的两个结果便是只出现一次的数字

代码示例

class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
       vector<int> result;
        int a = 0, b = 0, n = 0;
        for (vector<int>::iterator i = nums.begin(); i != nums.end(); ++i)
            a ^= *i;
        while((a >> n & 1) != 1)
            n++;
        a = 0;
        for (vector<int>::iterator i = nums.begin(); i != nums.end(); ++i)
        {
            if ((*i >> n & 1) == 1)
                a ^= *i;
            else
                b ^= *i;
        }
        result.push_back(a);
        result.push_back(b);
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值