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

    方法一:

    首先计算nums数组中所有数字的异或,记为xor
    令lowbit = xor & -xor,lowbit的含义为xor从低位向高位,第一个非0位所对应的数字
    例如假设xor = 6(二进制:0110),则-xor为(二进制:1010,-6的补码)
    则lowbit = 2(二进制:0010)

     1 class Solution {
     2 public:
     3     vector<int> singleNumber(vector<int>& nums) {
     4         int size=nums.size();
     5         if(size==0||nums.empty())
     6             return vector<int>();
     7         int diff=0;
     8         for(auto &ele:nums)
     9             diff^=ele;
    10         vector<int> res(2,0);
    11         diff&=-diff;//从低位向高位,第一个非0位所对应的数字
    12         for(auto &ele:nums)
    13             if(diff&ele)
    14                 res[0]^=ele;
    15             else
    16                 res[1]^=ele;
    17         return res;
    18     }
    19 };

     方法二:

     1 class Solution {
     2 public:
     3     vector<int> singleNumber(vector<int>& nums) {
     4         int size=nums.size();
     5         if(size==0||nums.empty())
     6             return vector<int>();
     7         int sum=0;
     8         for(auto &ele:nums)
     9             sum^=ele;
    10         vector<int> res(2,0);
    11         //从低位向高位,第一个非0位所对应的数字
    12         int n=1;
    13         while((sum&n)==0)
    14             n=n<<1;
    15         for(auto &ele:nums)
    16             if(n&ele)
    17                 res[0]^=ele;
    18             else
    19                 res[1]^=ele;
    20         return res;
    21     }
    22 };
  • 相关阅读:
    mysqldump详解
    mysql忽略表中的某个字段不查询
    mysqldumpslow基本使用
    xtrabakcup基本用法 安装、全量备份恢复、增量备份恢复
    Ubuntu--磁盘统计
    Ubuntu--硬盘的挂载与卸载
    Ubuntu--文件属性权限管理(command: chmod, chown)
    Ubuntu--useradd指令使用
    Ubuntu--安装sshd开启远程登陆服务
    Ubuntu--虚拟机中Ubuntu系统时间与windows不同步
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8536847.html
Copyright © 2011-2022 走看看