美文网首页
Java 算法 - Single Number III

Java 算法 - Single Number III

作者: 琼珶和予 | 来源:发表于2019-07-07 22:47 被阅读0次

    题意

    Given an array of numbers nums, in which exactly two elements appear only once and all the 
    other elements appear exactly twice. Find the two elements that appear only once.
    

    样例

    Input:  [1,2,1,3,2,5]
    Output: [3,5]
    

    1. 解题思路

      相信大家做过其他类似的题,就是从很多数中找出其中一个只出现过一次的数字,这种题的解决方法就是一个异或到底就能得出正确答案了。
      但是本题出现过一次的数字不是一个,而是两个,这个该怎么来做呢?其实是类似的思想,一个异或到底最终得到的值就是那两个数字的异或值,此时我们该怎么来分解呢?
      我们这样来思考,这两个数字不同,那么bit位上肯定有一位不同,我们就根据这一位bit位来分解出两个数字来。

    2. 代码

        public int[] singleNumber(int[] nums) {
            int k = 0;
            // 求出所有的异或值
            for (int i : nums) {
                k ^= i;
            }
            // 找到不相同的bit位,可能有多位,我们只需要其中一位就行了
            int lowestOneBit = Integer.lowestOneBit(k);
            int a = 0;
            int b = 0;
            for (int i : nums) {
                // 分解出两个数字,至于为什么这么分解,大家自行体会吧。。。。。。
                if ((lowestOneBit & i) != 0) {
                    a ^= i;
                } else {
                    b ^= i;
                }
            }
            return new int[]{a, b};
        }
    

    相关文章

      网友评论

          本文标题:Java 算法 - Single Number III

          本文链接:https://www.haomeiwen.com/subject/gzxwhctx.html