zoukankan      html  css  js  c++  java
  • 算法题:只出现一次的数字 三

    描述

    给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。

    示例 :

    输入: [1,2,1,3,2,5]
    输出: [3,5]
    注意:

    结果输出的顺序并不重要,对于上面的例子, [5, 3] 也是正确答案。
    你的算法应该具有线性时间复杂度。你能否仅使用常数空间复杂度来实现?

    链接:https://leetcode-cn.com/problems/single-number-iii

    思路

    先全部异或,得到的结果是最后两个数的异或值,从结果中找出一个为1的位diff(必定存在至少一个1),用这个位来重新区分原数组,遍历数组,将和diff与不为0的数全部异或,和diff与为0的数全部异或,最后两个数就是结果。为啥可行?因为相同的两个数所有位相同,必定成对出现在上述两种情况之一,不可能分开出现,最后异或全部抵消。

    代码

    class Solution {
    public:
        vector<int> singleNumber(vector<int>& nums) {
            int _xor = 0;
            for (int n : nums) _xor ^= n;
    
            int diff = 0;
            for (int i = 0;i < 32;i++) {  // 从低位开始找到第一个不为0的位
                if (_xor & (1 << i)) {
                    diff = 1 << i;
                    break;
                }
            }
            int a = 0, b = 0;
            for (int n : nums) {
                if (n & diff) a ^= n;
                else b ^= n;
            }
    
            return {a, b};
        }
    };
    

    复杂度
    时间复杂度:O(n)
    空间复杂度:O(1)

  • 相关阅读:
    The while statement
    App server 与 Web server之间的区别
    Keyboard input
    Recursion
    Conditionals
    TurtleWorld Exercises
    Python TurtleWorld configuration and simple test
    Why functions
    The python programing language
    性能测试3 方法
  • 原文地址:https://www.cnblogs.com/dinjufen/p/14342513.html
Copyright © 2011-2022 走看看