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

    Given an integer array 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. You can return the answer in any order.

    Follow up: Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

    Example 1:

    Input: nums = [1,2,1,3,2,5]
    Output: [3,5]
    Explanation:  [5, 3] is also a valid answer.
    

    Example 2:

    Input: nums = [-1,0]
    Output: [-1,0]
    

    Example 3:

    Input: nums = [0,1]
    Output: [1,0]
    

    Constraints:

    • 1 <= nums.length <= 30000
    •  Each integer in nums will appear twice, only two integers will appear once.
     
    class Solution {
    public:
        vector<int> singleNumber(vector<int>& nums) {
            //先将所有数字异或
            vector<int> res(2,0);
            int Xor = 0;
            for(int i=0;i<nums.size();i++){
                Xor ^= nums[i];
            }
            //res就是不重复的两个数的异或值。
            //例如 3 5:  (011  ^ 101 = 110)
            //需要根据这个异或值将原数组再分为两个数组:3/5分开
            //异或值的最低位的1就可以将两个数分开
            //法一
    //         int mask = 1;
    //         //bug !的优先级比&高
    //         while(!(Xor & mask)){
    //             mask <<= 1;
    //         }
            //法二
            //diff与自己的补码相与。得到3,5的从低位到高位的第一个不同的元素位置。3:011  5:101  101&010=010....
             //diff变成了仅有1个1,其它位置都为0的数,且那个1就是a和b第一个不相同的位置,这样就能区分开a和b了
            int mask = 1;
            mask = Xor & (-Xor);
            
            for(int i=0;i<nums.size();i++){
                if(nums[i]&mask){
                    res[0] ^= nums[i];
                }else{
                    res[1] ^= nums[i];
                }
            }
            return res;
        }
    };
  • 相关阅读:
    linux进程管理类
    linux关机重启指令
    linux分区及磁盘挂载
    linux的运行级别
    property
    访问限制机制
    类的组合与封装
    继承与派生
    logging模块
    re模块
  • 原文地址:https://www.cnblogs.com/wsw-seu/p/13676019.html
Copyright © 2011-2022 走看看