0260. Single Number III (M)

Single Number III (M)

題目

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.javascript

Example:java

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?

題意

給定一個數組,其中只有兩個數只出現了一次,其餘全部數都出現了兩次。要求找出這兩個數。app

思路

  1. 最簡單的作法就是使用Set進行操做,將已出現過的從Set中除去,將未出現過的加入到Set中。最後留下的就是要找的兩個數。spa

  2. 與 0136. Single Number 使用的方法相同,用異或找出這兩個數a和b,具體方法以下:code

    1. 對全部數進行異或,獲得的結果就是a和b的異或(相同的數異或會抵消獲得0),記爲xor。
    2. 由於a和b是不一樣的數,因此它們二進制的某一位一定不同,從右到左找到xor中第一個1(至關於從右到左找到a和b二進制第一個不一樣的位),記爲pos。如:3 ^ 5 = 011 ^ 101,pos = 010。
    3. 將nums中全部的數與pos相與,能夠將結果分爲兩組,區別在於對應二進制位上的數不一樣,而a和b必定分屬於這兩個組。
    4. 接着問題就變成和136同樣的狀況,將兩組數分別異或,獲得的就是a和b。

代碼實現

Java

Set

class Solution {
    public int[] singleNumber(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            if (set.contains(num)) {
                set.remove(num);
            } else {
                set.add(num);
            }
        }
        int[] ans = new int[set.size()];
        int index = 0;
        for (int num : set) {
            ans[index++] = num;
        }
        return ans;
    }
}

位操做

class Solution {
    public int[] singleNumber(int[] nums) {
        int[] ans = new int[2];
        int xor = 0;
        for (int num : nums) {
            xor ^= num;
        }
        int pos = 1;
        while ((xor & pos) == 0) {
            pos <<= 1;
        }
        for (int num : nums) {
            if ((num & pos) == 0) {
                ans[0] ^= num;
            } else {
                ans[1] ^= num;
            }
        }
        return ans;
    }
}

JavaScript

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var singleNumber = function (nums) {
  let xor = 0
  for (let num of nums) {
    xor ^= num
  }
  let pos = 1
  while (!(pos & xor)) {
    pos <<= 1
  }
  let a = 0
  let b = 0
  for (let num of nums) {
    if (num & pos) {
      a ^= num
    } else {
      b ^= num
    }
  }
  return [a, b]
}

參考ip

LeetCode 260. Single Number III 題解element

相關文章
相關標籤/搜索