Woodyiiiiiii / LeetCode

My private record of Leetcode solution

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

LeetCode 260. Single Number III

Woodyiiiiiii opened this issue · comments

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.

Example:

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

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

题目大意是一个非空数组中,有两个数出现一次,其他数都出现两次,找出这两个只出现了一次的数。结果数组顺序不重要。空间复杂度O(1),时间复杂度O(n)。

思路是把数组分成两部分,两个部分分别包含一个只出现了一次的数,然后对每个部分进行遍历异或,就可以找出这两个数。承接了Single Number I的**。

问题是如何把数组分开判断呢,首先对整个数组遍历异或,得到的数将会是那两个不相同的数异或的结果,我们要对这个结果作为一个判断条件,接下来就是找到这个结果最右位为1的数,对它的相反数相与,得到的就是最右位为1的数,因为最右位为1表示这位的右边都是0,相反数是取补码,则取反加一,相反数的最右位是1,后为0,跟数本身相同,而这个最右位以前的位数都是与相反数相反的。然后以此作为判断条件if语句对数组进行分隔,分别遍历两部分异或即可。

class Solution {
    public int[] singleNumber(int[] nums) {
        int diff = 0;
        int[] result = new int[2];
        for (int v : nums) {
            diff ^= v;
        }
        diff &= -diff;
        for (int v : nums) {
            if ((diff & v) != 0) result[0] ^= v;
            else result[1] ^= v;
        }
        
        return result;
    }
}

参考资料:

  1. LeetCode原题
  2. grandyang题解