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

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

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

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param nums int整型一维数组 
     * @return int整型一维数组
     */
    public int[] FindNumsAppearOnce (int[] nums) {
        // write code here
	  	// 首先,所有数进行异或
        int eor = 0;
        for (int x : nums) eor ^= x;
        // 提取出最右的1
        int rightOne = eor & (-eor);
        int onlyOne = 0;
	  	// 所有包含最右的1的数异或,就能确定出其中一个仅出现一次的数
        for (int x : nums) {
            if ((x & rightOne) != 0) onlyOne ^= x;
        }
	  	// 再进行异或确定出另一个仅出现一次的数
        int[] ans = {onlyOne, eor ^ onlyOne};
        Arrays.sort(ans);
        return ans;
    }
}

线性表基础 文章被收录于专栏

链表、递归、栈

全部评论

相关推荐

ldf李鑫:不说公司名祝你以后天天遇到这样的公司
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务