Exemplo n.º 1
0
    13: "d",
    14: "e",
    15: "f",
}


class Solution:
    def toHex(self, num: int) -> str:
        if num == 0:
            return "0"
        if num < 0:
            return self.toHex((((2**32) - 1) ^ (-num)) + 1)

        a, b = divmod(num, 16)
        if a == 0:
            return n10_to_n16[b]
        else:
            return self.toHex(a) + n10_to_n16[b]


# @lc code=end
from tool import t

f = Solution().toHex
t(f(0), "0")
t(f(1), "1")
t(f(9), "9")
t(f(10), "a")
t(f(26), "1a")
t(f(-1), "ffffffff")
Exemplo n.º 2
0
#

# @lc code=start

valid_numbers = set([str(i) for i in range(1, 27)])


class Solution:
    def numDecodings(self, s: str) -> int:
        # dp[i] 表示 s[i:] 能够表示为多少个单词
        dp = [0] * (len(s) + 1)

        dp[len(s)] = 1

        for i in range(len(s) - 1, -1, -1):
            if s[i] in valid_numbers:
                dp[i] += dp[i + 1]
            if i != len(s) - 1 and s[i:i + 2] in valid_numbers:
                dp[i] += dp[i + 2]
        return dp[0]


# @lc code=end

if __name__ == "__main__":
    from tool import t

    f = Solution().numDecodings
    t(f("12"), 2)
    t(f("226"), 3)
        def is_safe(index: int) -> bool:
            if safe_map[index] is None:
                if not graph[index]:
                    safe_map[index] = True
                else:
                    safe_map[index] = False
                    has_unsafe = False
                    for next_index in graph[index]:
                        if not is_safe(next_index):
                            has_unsafe = True
                            break
                    if not has_unsafe:
                        safe_map[index] = True
            return safe_map[index]

        result = []
        for i in range(len(graph)):
            if is_safe(i):
                result.append(i)
        return result


# @lc code=end
if __name__ == "__main__":
    from tool import t

    f = Solution().eventualSafeNodes
    t(f([[1, 2], [2, 3], [5], [0], [5], [], []]), [2, 4, 5, 6])
    t(f([[1, 2, 3, 4], [1, 2], [3, 4], [0, 4], []]), [4])
Exemplo n.º 4
0
        return s

    # def minSteps(self, n: int) -> int:
    #     if n == 1:
    #         return 0

    #     @lru_cache
    #     def run(screen: int, pasted: int) -> int:
    #         assert screen + pasted <= n
    #         if screen + pasted == n:
    #             return 1
    #         elif screen + pasted < n:
    #             # Paste
    #             case1 = 1 + run(screen + pasted, pasted)
    #             # Copy and Paste
    #             case2 = 2 + run(2 * screen, screen)
    #             return min(case1, case2)
    #         else:
    #             return 1001

    #     return run(1, 1) + 1


# @lc code=end
if __name__ == "__main__":
    from tool import t

    f = Solution().minSteps
    t(f(3), 3)
    t(f(4), 4)
Exemplo n.º 5
0
                while 0 <= i < m and 0 <= j < n:
                    result.append(matrix[i][j])
                    i -= 1
                    j += 1
            else:
                if line < n:
                    i = 0
                    j = line
                else:
                    j = n - 1
                    i = line - j

                assert i + j == line

                while 0 <= i < m and 0 <= j < n:
                    result.append(matrix[i][j])
                    i += 1
                    j -= 1
        return result
        return result


# @lc code=end
if __name__ == "__main__":
    from tool import t

    f = Solution().findDiagonalOrder
    t(f([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [1, 2, 4, 7, 5, 3, 6, 8, 9])
    t(f([[2, 3]]), [2, 3])
Exemplo n.º 6
0
#

# @lc code=start
from typing import List


class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if i == 0 and j == 0:
                    grid[0][0] = -grid[0][0]
                elif i == 0:
                    grid[i][j] = grid[i][j - 1] - grid[i][j]
                elif j == 0:
                    grid[i][j] = grid[i - 1][j] - grid[i][j]
                else:
                    grid[i][j] = max(grid[i][j - 1],
                                     grid[i - 1][j]) - grid[i][j]
                # assert grid[i][j] <= 0, debug
        return -grid[len(grid) - 1][len(grid[0]) - 1]


# @lc code=end
if __name__ == "__main__":
    from tool import t

    f = Solution().minPathSum
    t(f([[1, 3, 1], [1, 5, 1], [4, 2, 1]]), 7)
    t(f([[1, 2, 3], [4, 5, 6]]), 12)
Exemplo n.º 7
0
        if k == 0:
            for i in range(len(nums) - 1):
                if nums[i] == nums[i + 1] == 0:
                    return True
            return False
        else:
            # mods[x] = v 表示 sum(nums[0:x]) % k == v
            mods = {0: 0}  # magic!
            mod = 0
            for index, num in enumerate(nums):
                mod = (mod + num) % k
                if mod in mods:
                    if index + 1 - mods[mod] >= 2:
                        return True
                else:
                    mods[mod] = index + 1
            return False


# @lc code=end

if __name__ == "__main__":
    from tool import t

    f = Solution().checkSubarraySum

    t(f([23, 2, 4, 6, 7], 6), True)
    t(f([1, 1], 2), True)
    t(f([1, 0], 2), False)

Exemplo n.º 8
0
    def nthUglyNumber(self, n: int) -> int:
        if n == 0:
            return []

        seq = [1]
        i2, i3, i5 = 0, 0, 0

        while len(seq) < n:
            n2, n3, n5 = seq[i2] * 2, seq[i3] * 3, seq[i5] * 5
            if n2 <= n3 and n2 <= n5:
                i2 += 1
                if n2 > seq[-1]:
                    seq.append(n2)
            if n3 <= n2 and n3 <= n5:
                i3 += 1
                if n3 > seq[-1]:
                    seq.append(n3)
            if n5 <= n2 and n5 <= n3:
                i5 += 1
                if n5 > seq[-1]:
                    seq.append(n5)
        return seq[-1]


# @lc code=end
if __name__ == "__main__":
    from tool import t

    f = Solution().nthUglyNumber
    t(f(10), 12)
Exemplo n.º 9
0
class Solution:
    def countBits(self, num):
        if num == 0:
            return [0]

        result = [0]

        while True:
            loop_size = len(result)
            for i in range(loop_size):
                result.append(result[i] + 1)
                if len(result) > num:
                    break
            if len(result) > num:
                break

        return result


# @lc code=end

if __name__ == "__main__":
    from tool import t

    f = Solution().countBits

    t(f(0), [0])
    t(f(1), [0, 1])
    t(f(2), [0, 1, 1])
    t(f(3), [0, 1, 1, 2])
Exemplo n.º 10
0
        ps: List[tuple] = []
        max_weight = 0
        for point, weight in counter.items():
            ps.append((point[0], point[1], weight))
            max_weight = max(max_weight, weight)

        all_km: Dict[tuple, int] = {}
        while ps:
            x1, y1, w1 = ps.pop()
            curr_km: Dict[tuple, int] = defaultdict(int)
            for x2, y2, w2 in ps:
                k, m = cal_km(x1, y1, x2, y2)
                if (k, m) not in all_km:
                    curr_km[(k, m)] += w2
            assert len(curr_km.keys() & all_km.keys()) == 0
            for km, point_num in curr_km.items():
                all_km[(km)] = point_num + w1
        return max(all_km.values()) if all_km else max_weight


# @lc code=end
if __name__ == "__main__":
    from tool import t

    f = Solution().maxPoints
    t(f([[1, 1], [2, 2], [3, 3]]), 3)
    t(f([[1, 1], [3, 2], [5, 3], [4, 1], [2, 3], [1, 4]]), 4)
    t(f([[0, 0]]), 1)

Exemplo n.º 11
0
            if value >= remainder:
                dp[choosable] = True
                return True
            else:
                next_choosable = choosable - (1 << i)
                assert 1 & (next_choosable >> i) == 0
                if not can_i_win(next_choosable, remainder - value, dp):
                    dp[choosable] = True
                    return True
    dp[choosable] = False
    return False


class Solution:
    def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
        if sum(list(range(1, maxChoosableInteger + 1))) < desiredTotal:
            return False
        return can_i_win((1 << (maxChoosableInteger)) - 1, desiredTotal, {})


# @lc code=end
if __name__ == "__main__":
    f = Solution().canIWin
    from tool import t

    t(f(10, 11), False)
    t(f(10, 0), True)
    t(f(10, 1), True)
    t(f(19, 79), True)
    t(f(18, 79), True)
                return True
        return False


class Solution:
    def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:
        allowed_map: Dict[str, List[str]] = defaultdict(list)
        for a, b, c in allowed:
            allowed_map[a + b].append(c)
        return pyramid_transition(bottom, allowed_map)


# @lc code=end

if __name__ == "__main__":
    from tool import t

    t(list(iter_product([["A", "B"], ["C", "D", "E"]])), [
        "AC",
        "AD",
        "AE",
        "BC",
        "BD",
        "BE",
    ])
    t(list(iter_product([["A", "B"], ["C", "D", "E"], []])), [])

    f = Solution().pyramidTransition
    t(f("BCD", allowed=["BCG", "CDE", "GEA", "FFF"]), True)
    t(f("AABA", allowed=["AAA", "AAB", "ABA", "ABB", "BAC"]), False)
Exemplo n.º 13
0
# What if the matrix is stored on disk, and the memory is limited such that you
# can only load at most one row of the matrix into the memory at once?
# What if the matrix is so large that you can only load up a partial row into
# the memory at once?
#
#
#

from typing import List

# @lc code=start
class Solution:
    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
        for i in range(len(matrix) - 1):
            r1 = matrix[i]
            r2 = matrix[i + 1]
            for j in range(len(r1) - 1):
                if r1[j] != r2[j + 1]:
                    return False
        return True


# @lc code=end
if __name__ == "__main__":
    from tool import t

    f = Solution().isToeplitzMatrix
    t(f([[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]), True)
    t(f([[1, 2], [2, 2]]), False)

Exemplo n.º 14
0
            return []

        # int(S[0:i]) + int(S[i:j]) = int(S[j:k])
        for i in range(1, len(s)):
            n1 = int(s[0:i])
            if str(n1) != s[0:i] or n1 > MAX:
                continue

            for j in range(i + 1, len(s) - 1):
                n2 = int(s[i:j])
                if str(n2) != s[i:j] or n2 > MAX:
                    continue

                fib = is_fibonacci(n1, n2, s[j:])
                if fib and all(f <= MAX for f in fib):
                    return [n1, n2, *fib]
        return []


# @lc code=end
if __name__ == "__main__":
    from tool import t

    f = Solution().splitIntoFibonacci
    t(f("123456579"), [123, 456, 579])
    t(f("11235813"), [1, 1, 2, 3, 5, 8, 13])
    t(f("112358130"), [])
    t(f("0123"), [])
    # t(f("1101111"), [110, 1, 111])
    t(f("1101111"), [11, 0, 11, 11])
Exemplo n.º 15
0
# @lc code=start

from typing import List


class Solution:
    def find132pattern(self, nums: List[int]) -> bool:
        smallest = float('inf')
        stack = []
        for i in nums:
            while stack and i >= stack[-1][-1]:
                stack.pop()
            if stack and i > stack[-1][0]:
                return True
            stack.append((smallest,i))
            smallest = min(smallest,i)
        return False

# @lc code=end
if __name__ == "__main__":
    f = Solution().find132pattern
    from tool import t

    # t(f([1, 2, 3, 4]), False)
    # t(f([3, 1, 4, 2]), True)
    # t(f([-1, 3, 2, 0]), True)
    # t(f([1, 3, 2, 4, 5, 6, 7, 8, 9, 10]), True)
    # t(f([-2, 1, 1, -2, 1, 2]), False)
    t(f([10, 12, 6, 8, 3, 11]), True)

Exemplo n.º 16
0
# Your Twitter object will be instantiated and called as such:
# obj = Twitter()
# obj.postTweet(user_id,tweet_id)
# param_2 = obj.getNewsFeed(user_id)
# obj.follow(follower_id,followee_id)
# obj.unfollow(follower_id,followee_id)
# @lc code=end

if __name__ == "__main__":
    from tool import t

    if True:
        twitter = Twitter()
        twitter.postTweet(1, 5)
        t(twitter.getNewsFeed(1), [5])

        twitter.follow(1, 2)

        twitter.postTweet(2, 6)

        t(twitter.getNewsFeed(1), [6, 5])

        twitter.unfollow(1, 2)
        t(twitter.getNewsFeed(1), [5])

    if True:
        twitter = Twitter()
        twitter.postTweet(1, 5)
        twitter.postTweet(1, 3)
        t(twitter.getNewsFeed(1), [3, 5])
    def _get_area(self, row, col):
        if row < 0 or col < 0:
            return 0
        else:
            return self.matrix[row][col]

    def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
        return (
            self._get_area(row2, col2)
            - self._get_area(row1 - 1, col2)
            - self._get_area(row2, col1 - 1)
            + self._get_area(row1 - 1, col1 - 1)
        )


# Your NumMatrix object will be instantiated and called as such:
# obj = NumMatrix(matrix)
# param_1 = obj.sumRegion(row1,col1,row2,col2)
# @lc code=end
if __name__ == "__main__":
    from tool import t

    matrix = [[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]
    f = NumMatrix(matrix)

    t(f.sumRegion(2, 1, 4, 3), 8)
    t(f.sumRegion(1, 1, 2, 2), 11)
    t(f.sumRegion(1, 2, 2, 4), 12)

def findMedianSortedArrays_v2(nums1: List[int], nums2: List[int]) -> float:
    pass


class Solution:
    def findMedianSortedArrays(self, nums1: List[int],
                               nums2: List[int]) -> float:
        return findMedianSortedArrays_v2(nums1, nums2)


# @lc code=end
if __name__ == "__main__":
    from tool import t

    f = Solution().findMedianSortedArrays

    import ipdb

    # ipdb.set_trace()

    for i in range(10):  # There is some random operations

        t(f([1, 3], [2]), 2)
        t(f([1, 2], [3, 4]), 2.5)
        t(f([0, 0], [0, 0]), 0)
        t(f([], [1]), 1)
        t(f([2], []), 2)
        t(f([1, 3], [2, 7]), 2.5)
        t(f([1, 2], [1, 2]), 1.5)
        res = 0
        max_len = 0
        for i in range(len(values)):
            l[i] = 1
            for j in range(0, i):
                if values[j] < values[i]:
                    l[i] = max(l[i], l[j] + 1)
            max_len = max(max_len, l[i])
        for i in range(len(values)):
            if l[i] == 1:
                c[i] = 1
            else:
                c[i] = 0
                for j in range(0, i):
                    if values[j] < values[i] and l[j] == l[i] - 1:
                        c[i] += c[j]
            if l[i] == max_len:
                res += c[i]

        return res


# @lc code=end
if __name__ == "__main__":
    from tool import t

    f = Solution().findNumberOfLIS
    t(f([1, 3, 5, 4, 7]), 2)
    t(f([2, 2, 2, 2, 2]), 5)
Exemplo n.º 20
0
        result = self.grayCode(n - 1)
        length = len(result)
        for i in range(length - 1, -1, -1):
            result.append((1 << (n - 1)) + result[i])
        return result


# @lc code=end
if __name__ == "__main__":
    from tool import t

    f = Solution().grayCode
    # fmt:off
    t(f(2), [int(i, 2) for i in [
        "00",
        "01",
        "11",
        "10",
    ]])
    t(f(3), [
        int(i, 2) for i in [
            '000',
            '001',
            '011',
            '010',
            '110',
            '111',
            '101',
            '100',
        ]
    ])
Exemplo n.º 21
0
        passed = {deadend: -1 for deadend in deadends}
        q = Queue()
        q.put(("0000", 0))

        while not q.empty():
            key, steps = q.get()
            if key in passed:
                continue

            if key == target:
                return steps
            passed[key] = steps

            for next_key in get_next_keys(key):
                if next_key not in passed:
                    q.put((next_key, steps + 1))
        return -1


# @lc code=end
if __name__ == "__main__":
    from tool import t

    f = Solution().openLock
    t(f(["8888"], "0009"), 1)
    t(f(["8888"], "0008"), 2)
    t(
        f(["8887", "8889", "8878", "8898", "8788", "8988", "7888", "9888"],
          "8888"), -1)