活跃农民
- 积分
- 868
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-11-29
- 最后登录
- 1970-1-1
|
06/22
• Missing number (unsorted)
○ Sol 1:
§ sum of first n numbers = n * (n + 1)//2
§ missing number = sum - array_sum
§ Time O(n), Space O(1) -> Overflow
○ Sol2:
§ Xor
§ assume a1 ^ a2 ^ a3 …a_n = A; a1 ^ a2 ^ a3 …a_n-1 = B => A^ B = a_n
§ two variables, one update with ^index, one update by ^ array[index]
§ Time O(n), Space O(1)
• Single Number II / Single Number
○ Sol1:
§ count appearance of 1 for all 32 bit
§ if number exists 3 times, the counts of 1 for each bits will be 0 or 3
• go through 32 bit,
® count all appearance of 1 on position i with num & (1 << i) == 1(1 << i)
® evlaute the counts modulo 3, if left 1 means the unique number have 1 on position I
single |= (count % 3) << i
® Finally, deal with the overflow in python: maximum value for int32 is 2^31 -1, so number more than that will be negative -> single - (1 << 31)
Time O(32n)
○ Sol2:
one: 每个bit表示这个位置上出现的1
two: 每个bit表示这个位置上是否出现了两个1,
如果相同位置上one和two的bit都是1, 说明这个位置上1出现了3次,那么将1从这两个里面同时移除(two 位置上为1,one必定为1)
§ x1, x2, mask
x2 ^= (x1 & i ) -> i的所有位置上的1是否同时出现在x1中, 如果是的话说明1在这个位置1起码出现了两次, 更新到x2
x1 ^= i -> 更新i的所有位置上的1到x1上, 如果已经出现过1, 还是1,如果未出现更新成1
mask = ~(x1 & x2) -> 找出相同位置上的x1和x2都为1的取反, 剩下的是只出现了一次1的位置
x2 &= mask
x1 &= mask -> 保留x1, x2里面只有x1为1的1
Time O(n)
○ 两种方法用的是相同思路,可以延伸至 K repeats, 第一个取模换成k
第二个k-1个variable表示这个位置的1出现了几次,if k-1 to 1 all have 1, then exclude all of them
• Single Number III
○ Sol1:
§ dictionary
§ Time O(N), Space O(1)
○ Sol2: Bit operation
§ get x = a ^ b by XOR all element in the array
§ the 1 bit in x means a and b have different bit in that position, depends on these we can separate all the numbers into two buckets
□ find the most right 1 bit in x (or any one of 1 bit in x) by x & - x
□ bucket one has number have 1 bit in that position;
bucket two has number have 0 bit in that position;
Then since all other numbers appear twice, therefore the left in each bucket by XOR is the unique number
§ Time O(N), Space O(1)
• Binary Number with Alternating Bits
○ prev = n & 1 find the last digit is 0 or 1
○ then move bit to the right by n <<= 1, and check the current last digit XOR with prev
§ cur = n & 1
§ if cur == prev: False
else: prev = cur
Time O(32) |
|