Leetcode 137. Single Number II

GoodJobJasper發表於2021-01-02

在這裡插入圖片描述
方法1: 136的升級版。依舊是bit manipulation。我感覺這題目老難了。我現在看了都沒咋看懂,更別說面試時候自己寫出來了。時間複雜n,空間複雜1.

class Solution {
  public int singleNumber(int[] nums) {
    int seenOnce = 0, seenTwice = 0;

    for (int num : nums) {
      // first appearence: 
      // add num to seen_once 
      // don't add to seen_twice because of presence in seen_once

      // second appearance: 
      // remove num from seen_once 
      // add num to seen_twice

      // third appearance: 
      // don't add to seen_once because of presence in seen_twice
      // remove num from seen_twice
        System.out.println(~seenTwice) ;
      seenOnce = ~seenTwice & (seenOnce ^ num);
        System.out.println(~seenOnce) ;
      seenTwice = ~seenOnce & (seenTwice ^ num);
    }

    return seenOnce;
  }
}

總結:

相關文章