260 Single Number III

来源:互联网 发布:数组转化为json 编辑:程序博客网 时间:2024/04/27 17:14

原题描述

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
原创粉丝点击