数组中只出现一次的数字

数组中只出现一次的数字

https://www.nowcoder.com/practice/e02fdb54d7524710a7d664d082bb7811?tpId=117&tqId=37773&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fjob-code-high%2Fquestion-ranking&tab=answerKey

//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public class Solution {
    public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
        int yh = 0;
        for(int i=0;i<array.length;i++){
            yh = yh ^ array[i];
        }
        int index = 1;
        //找到第一个二进制为1的位置
        while((index & yh) ==0){
            index = index << 1;
        }
        int res1 = 0;
        int res2 = 0;
        //按照该位置是否为1 分成两部分 分别异或  问题转化成两个数组中只有一个数字出现一次 其余数字都出现两次
        for(int a:array){
            if((a&index)==0) res1=res1 ^ a;
            else res2 = res2 ^ a;
        }
        num1[0] = res1;
        num2[0] = res2;
    }
}
全部评论

相关推荐

头像
不愿透露姓名的神秘牛友
04-29 12:10
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务