zoukankan      html  css  js  c++  java
  • 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:

    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; 

    可以这样做的原因是,一个数的负为它的反码加1, 如数00100100,反码是11011011,将其加一后变为11011100,可以看到,原数最右的一个1现在仍然是1,其他位与运算完后是0。这样两数与运算后结果为00000100,即只有最右的一个1。

    此外,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 };
  • 相关阅读:
    css笔记
    js面向对象开发之--元素拖拽
    git命令笔记
    数据扁平化笔记。
    手写冒泡排序
    ant design-Table组件实现每一行某个特定字段连续相同进行行合并。
    Array.prototype.reduce()。
    I/O多路复用
    TCP/IP四层体系结构
    TCP的三次握手和四次挥手,为什么?
  • 原文地址:https://www.cnblogs.com/fenshen371/p/4908206.html
Copyright © 2011-2022 走看看