Leetcode 137. Single Number II

Leetcode 137. Single Number II_第1张图片
方法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;
  }
}

总结:

你可能感兴趣的:(Leetcode,math,bitmap,leetcode)