LeetCode 4/28 每日一题

https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/

这个题把我虐到了,O(n)的时间复杂度,O(1)的空间复杂度,限制的死死地。然后仔细看题,重复的数据只出现两次,有两个数据是只出现一次的,这个很明显要求用位运算完成了,不然不会给这种要求的数据。但是位运算我也是鸡啊,好难。

class Solution {
    public int[] singleNumbers(int[] nums) {
        int x = 0;
        for(int a:nums){
            x ^= a;
        }
        int flag = x & (-x);
        int res = 0;
        for(int val :nums){
            if((flag & val) != 0){
                res ^= val;
            }
        }
        return new int[] {res, x^res};
    }
}
View Code

代码内容还是靠评论区实现的,位运算真的是太多骚操作了 T_T

最佳评论传送门

猜你喜欢

转载自www.cnblogs.com/ZJPaang/p/12792016.html