Single Number II

1.第一种解法的复杂度是O(32*n)

注意操作

# -*- coding:utf-8 -*-

import ctypes

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        array = []
        for i in range(32):
            array.append(0)

        res = 0
        for i in range(32):
            for num in nums:
                array[i] += (num >> i) & 1
            # 先判断该位是不是1, 再根据i左移, 再或运算即可
            res |= ((array[i] % 3) << i)
        ################################################################### 1
        '''本来可以导入模块的话,很简单
        return ctypes.c_int(res).value'''
        ################################################################### 2
        #转化成二进制的字符串,截掉前两个字符,再变成字符list,再转化成int的list
        strings = bin(res)[2:]
        if len(strings) < 32:    #正数可能不足32位,所以要补
            strings = '0' * (32 - len(strings)) + strings

        numlist = map(lambda x: ord(x) - ord('0'), list(strings))

        rest = 0
        for i in range(31):
            rest = rest * 2 + numlist[i+1]

        rest += numlist[0] * (-1) * 2147483648

        return rest


s = Solution()
s.singleNumber([1000,2,2,2,3,3,3,4,4,4])
# print s.singleNumber()

2.第2种解法的复杂度是O(n)

构造三进制,先只考虑ones, twos, threes为 1 bit的情况会更好

class Solution {
public:
    int singleNumber(int A[], int n) {
        int ones = 0;
        int twos = 0;
        int threes = 0;
        int i = 0;
        
        for(i = 0; i < n; i++){
            twos |= ones & A[i];
            ones ^= A[i];
            threes = ones & twos;
            ones &= ~threes;
            twos &= ~threes;
        }
        return ones;
    }
};

你可能感兴趣的:(Single Number II)