码迷,mamicode.com
首页 > 其他好文 > 详细

Single Number III - LeetCode

时间:2015-10-25 09:35:05      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

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:

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

思路:对所有数进行一次异或运算。运算结果为所求的两个数的异或结果。

因为两个数是不同的,因此结果必不为0。设该结果为res,其二进制形式必有几位是1。而根据异或运算规则,所求的两个数在这些位上一定有一个是1,一个是0。我们从这些位中随便取1位,然后将所有的数根据在这一位上是0还是1分成两组。则所求的两个数必然分别在这两个组内,此时分别再进行一次异或运算,就得到了两个数。

代码中 res随机取二进制为1的一位 用的是 res &= -res; 目前没完全搞懂为什么这样就必然对,暂且先记住。

此外,for (:)的写法也是第一次见。

 1 class Solution {
 2 public:
 3     vector<int> singleNumber(vector<int>& nums) {
 4         int res = 0;
 5         for (int num : nums)
 6             res ^= num;
 7         res &= -res;
 8         vector<int> ans = {0, 0};
 9         for (int num : nums)
10         {
11             if (res & num)
12                 ans[0] ^= num;
13             else ans[1] ^= num;
14         }
15         return ans;
16     }
17 };

 

Single Number III - LeetCode

标签:

原文地址:http://www.cnblogs.com/fenshen371/p/4908206.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!