zoukankan      html  css  js  c++  java
  • 【LeetCode】260. Single Number III

    Problems:

    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?

    Solution:

    把这道题分为Medium难度我就有点尴尬了= - =

    要求满足线性空间复杂度,用运算符解。

    首先,在原始数组中,只有有两个数只出现一次,其余数字均出现两次。我们对整个数组数字进行异或,最终得到的结果即等同于所求两数的异或值。

    因为两数不相同,所以至少在某一位上异或值为1,那么接下来,就要找出第一个为1的位数是第几位。用变量bit表示运算结果。

    最后遍历数组,对每个数和之前算出bit进行与运算,找出那两个数。

    Code(C++):

     1 class Solution {
     2 public:
     3     vector<int> singleNumber(vector<int>& nums) {
     4         int n = nums[0];
     5         
     6         int x = 0; 
     7         for(int n: nums)
     8             x^=n; //获取两数的异或值
     9         int bit;
    10         int num1 = 0,num2 = 0;    
    11         bit = x & ~(x-1);   //获取两数最低位不相同值的位数
    12         for(int n: nums)
    13         {   
    14             if(n & bit)
    15                 num1^=n;
    16             else
    17                 num2^=n;
    18         }
    19         return vector<int> {num1, num2};  
    20     }
    21 };
  • 相关阅读:
    BZOJ 1968: [Ahoi2005]COMMON 约数研究
    BZOJ 2463: [中山市选2009]谁能赢呢?
    BZOJ 2462: [BeiJing2011]矩阵模板
    hihoCoder 后缀自动机三·重复旋律6
    hihoCoder #1445 : 后缀自动机二·重复旋律5
    BZOJ 2179: FFT快速傅立叶
    BZOJ 3926: [Zjoi2015]诸神眷顾的幻想乡
    BZOJ 2946: [Poi2000]公共串
    BZOJ 2882: 工艺
    SPOJ LCS2
  • 原文地址:https://www.cnblogs.com/liez/p/5492062.html
Copyright © 2011-2022 走看看