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 };
  • 相关阅读:
    软工结对第一次作业
    16061023-软件工程第1次作业
    OO最后一次总结
    OO第三次博客作业
    OO第二次博客作业
    OO第一次博客
    提问回顾与个人总结
    软件工程第一次阅读作业
    test个人博客
    软件工程结对作业
  • 原文地址:https://www.cnblogs.com/liez/p/5492062.html
Copyright © 2011-2022 走看看