题解 | #数组中只出现一次的两个数字# 妙蛙 位运算

数组中只出现一次的两个数字

https://www.nowcoder.com/practice/389fc1c3d3be4479a154f63f495abff8

class Solution {
// 题解中 使用位运算 更妙 不依赖哈希表
// https://www.nowcoder.com/practice/389fc1c3d3be4479a154f63f495abff8?tpId=295&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D295
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param array int整型vector 
     * @return int整型vector
     */
    vector<int> FindNumsAppearOnce(vector<int>& array) {
        // write code here

        int n = array.size();

        vector<int> ans(2,0);

        // a, b 就是那唯2的元素 全部异或
        int temp = 0;
        for(int i=0; i<n; ++i)
        {
            temp^=array[i];
        }

        int k = 1;
        while((k&temp)==0)
        {
            k <<=1; // 从低位到高位啊 找到首个 a和b不同的位置
        }

        // 在遍历一次 分组记录 a b
        for(int i=0; i<n; ++i)
        {
            if((k & array[i])==0)
            {
                // 会包含较小的数 两者中 有一个值计算一次 就是本身
                ans[0] ^= array[i];
            }
            else
            {
                ans[1] ^= array[i];
            }

        }
        if(ans[0]>ans[1]) swap(ans[0], ans[1]); 
        return ans;

    }
};

空间复杂度就为0了

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务