leecode 解题总结:260. Single Number III

来源:互联网 发布:中式现代服装 知乎 编辑:程序博客网 时间:2024/06/14 22:35
#include <iostream>#include <stdio.h>#include <vector>#include <string>using namespace std;/*问题:Given an array of numbers nums, in which exactly two elements appear only once and all the otherelements 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?分析:数组中只有两个数各自出现一次,其余数出现两次。需要在线性时间和常量空间求解该问题。可以通过依次比较最低位,次最低位...上值来对两个数所在范围不断划分,并删除各自范围中与两者异或低位不等的地方。距离:1 2 1 3 2 5数组中所有元素异或结果=3^5=0011 ^ 0101 = 0110=61: 00012: 00103: 00115: 0101根据异或结果6的最低位为0,知道两个各出现一次的数,异或结果为0将所有数按照最低位是否为0分成两组:最低位为0的是: 2,为1的是:1,3,5异或结果6的第二位(从右往左数)为1,强所有数按照最低位是否为1分为两组:以上分析错误:参见leecode:https://leetcode.com/problems/single-number-iii/?tab=Solutions最重要的就是利用两个数的异或结果和肯定不为0(两个各自出现一次的数不同)寻找到最低位的1,或者其他位的1,这都无所谓,然后按照该位是否为1将数组划分成两部分,分别异或每一个组中必定有各自出现1次的数,和出现两次的相同数字(如果有的话),这样出现两次的不会影响到该组内的结果输入:61 2 1 3 2 5输出:3 5关键:1 最重要的就是利用两个数的异或结果和肯定不为0(两个各自出现一次的数不同)寻找到最低位的1,或者其他位的1,这都无所谓,然后按照该位是否为1将数组划分成两部分,分别异或每一个组中必定有各自出现1次的数,和出现两次的相同数字(如果有的话),这样出现两次的不会影响到该组内的结果,就会得到该组内那个只出现1次的数字*/class Solution {public:    vector<int> singleNumber(vector<int>& nums) {vector<int> result;        if(nums.empty()){return result;}int size = nums.size();int answer = 0;for(int i = 0 ; i < size ; i++){answer ^= nums.at(i);}//异或后的结果需要寻找出最低位的1,用一个1不断向右查找即可int value = 1;int index = -1;for(int i = 0; i < 32 ; i++){//如果找到结果,记录位置if( 0 != ( (value << i) & answer ) ){index = i;break;}}if(-1 == index){return result;}//按照最低位是否为1进行划分value = (1 << index);int answer1 = 0;int answer2 = 0;for(int i = 0 ; i < size ; i++){if(0 == (value & nums.at(i))){answer1 ^= nums.at(i);}else{answer2 ^= nums.at(i);}}result.push_back(answer1);result.push_back(answer2);return result;    }};void print(vector<int>& result){if(result.empty()){cout << "no result" << endl;return;}int size = result.size();for(int i = 0 ; i < size ; i++){cout << result.at(i) << " " ;}cout << endl;}void process(){ vector<int> nums; int value; int num; Solution solution; vector<int> result; while(cin >> num ) { nums.clear(); for(int i = 0 ; i < num ; i++) { cin >> value; nums.push_back(value); } result = solution.singleNumber(nums); print(result); }}int main(int argc , char* argv[]){process();getchar();return 0;}

0 0
原创粉丝点击