hon9g / algorithms

TIL: to keep practice on algorithms
6 stars 2 forks source link

cpps: bit manipulation #10

Open hon9g opened 5 years ago

hon9g commented 5 years ago

modulabs cpps study ✔️ Problems from LeetCode 🌐

# title my solution
1 Subsets O(N 2^N)/O(N 2^N)✔️
2 Single Number O(N)/O(1)✔️
3 Single Number II
4 Majority Element O(N lg N)/O(1)✔️
5 Bitwise AND of Numbers Range if len(bin((m)) == len(bin(n)) O(n-m) else O(n) / O(1)
6 Missing Number
7 Sum of Two Integers
8 UTF-8 Validation
hon9g commented 5 years ago

Clear

hon9g commented 5 years ago

Q1. Subsets

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)
        result = []
        for i in range(2**n):
            mask = str(bin(i))[2:]
            m = len(mask)
            if m < n:
                mask = '0'*(n-m) + mask
            sub = []
            for j in range(n):
                if mask[j] == '1':
                    sub.append(nums[j])
            result.append(sub)
        return result
hon9g commented 5 years ago

Q2. Single Number

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        n = 0
        for num in nums:
            n ^= num
        return n   
hon9g commented 5 years ago

Q3. Single Number II

hon9g commented 5 years ago

Q4. Majority Element

solution with sorting + counting

hon9g commented 5 years ago

Q5. Bitwise AND of Numbers Range

brute force