zoukankan      html  css  js  c++  java
  • Single Number III

    Description:

    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?

    Code:

        vector<int> singleNumber(vector<int>& nums) {
            vector<int>result;
            if (nums.size() < 2)
                return result;
            int xorAll = 0;
            for (int i = 0; i < nums.size(); ++i)
                xorAll^=nums[i];
            unsigned int x = 1;
            while ((xorAll & x) == 0)
            {
                x=x<<1;
            }
            int result1=0,result2=0;
            for (int j = 0; j < nums.size(); ++j)
            {
                if ((nums[j]&x) == 0)
                    result1^=nums[j];
                else
                    result2^=nums[j];
            }
            result.push_back(result1);
            result.push_back(result2);
            return result;
        }

    PS:

    思路很清晰,但是写代码的是后老在细节出错,主要是两个判断条件要注意

  • 相关阅读:
    Thinkcmf:页面常用函数
    thinkcmf开发--关于控制器
    thinkcmf 常用操作
    Thinkcmf 二次开发
    Sublime Text 3 快捷键精华版
    php动态更改post_max_size, upload_max_filesize等值
    Jquery使用小技巧
    jQuery常用方法和函数
    三层架构
    JDBC
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4752002.html
Copyright © 2011-2022 走看看