0
点赞
收藏
分享

微信扫一扫

【图论】最短路(二)

花姐的职场人生 2024-05-26 阅读 8
算法

260. 只出现一次的数字 III - 力扣(LeetCode)

 

class Solution {
    public int[] singleNumber(int[] nums) {
        //通过异或操作,使得最终结果为两个只出现一次的元素的异或值
        int filterResult = 0;
        for(int num:nums){
            filterResult^=num;
        }

        //计算首个1(从右侧开始)的二进制位的值
        int bitValue = filterResult&-filterResult;
        //以首个为1的二进制位将原数组分为两部分并进行异或运算,最终结果为两个题解
        int oneResult = 0,twoResult = 0;
        for(int num:nums){
            if((num&bitValue)>0){
                oneResult ^= num;
            }
            else{
                twoResult^=num;
            }
        }
        return new int[]{oneResult,twoResult};

        
    }
}
class Solution {
    public int[] singleNumber(int[] nums) {
        //通过异或操作,使得最终结果为两个只出现一次的元素的异或值
        int filterResult = 0;
        for(int num:nums){
            filterResult^=num;
        }

        //计算首个1(从右侧开始)的二进制位的值
        int bitValue = filterResult&(filterResult-1)^filterResult;
        //以首个为1的二进制位将原数组分为两部分并进行异或运算,最终结果为两个题解
        int oneResult = 0,twoResult = 0;
        for(int num:nums){
            if((num&bitValue)>0){
                oneResult ^= num;
            }
            else{
                twoResult^=num;
            }
        }
        return new int[]{oneResult,twoResult};

        
    }
}
举报

相关推荐

0 条评论