from typing import List
from test_script import speedtest
from collections import Counter


class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        return Counter(nums).most_common(1)[0][0]

    def findDuplicate_fast(self, nums: List[int]) -> int:
        s = set()
        for num in nums:
            if num in s:
                return num
            s.add(num)
        return -1


import bisect

nums = list(range(100000))
bisect.insort_right(nums, 10000)
speedtest((Solution().findDuplicate, Solution().findDuplicate_fast), [nums])
        minLen = 2 ** 31 - 1
        # 当窗口越界,结束循环
        while windowEnd < len(s):
            # 首先是挪动窗口的尾部
            if s[windowEnd] in t:  # 只需要管t中的那几个字符
                nowCounter[s[windowEnd]] += 1  # nowCounter记录(由于是右开区间所以要先修订nowCounter)
                if nowCounter[s[windowEnd]] == targetCounter[s[windowEnd]]:  # 检查这个字符有没有达到t中的出现频率
                    valid += 1  # 这个字符达到了,此时[windowStart, windowEnd+1)是满足题意的
            windowEnd += 1  # 由于是右开区间,所以要++
            # 然后是挪动窗口的首部
            while valid == len(targetCounter):  # 当前状态一直满足题目要求时,收缩首部
                # 记录答案
                if windowEnd - windowStart < minLen:
                    minLen = windowEnd - windowStart
                    minStr = s[windowStart:windowEnd]
                # 和上面的逻辑类似,不过因为左闭区间,所以后修订nowCounter
                if s[windowStart] in t:
                    if nowCounter[s[windowStart]] == targetCounter[s[windowStart]]:  # 如果删掉该字符,valid会受到影响
                        valid -= 1
                    nowCounter[s[windowStart]] -= 1
                windowStart += 1
        return minStr


speedtest((Solution().minWindow_violent, Solution().minWindow, Solution().minWindow_noCounter), (
    "sshcxyfgecymhhpmjrfjlmiwkaunetxwleajdfrjhrxrymdkdltoxbmjdhwhatfoafzfkqquhnlhcqrfdmwdnkmtrlaueiignjlazdwirhrtzladxygnjugcfiymqgsgpggqjcaclsxmdarcyzpjuxobimnytigkqodzsdedxbscblfclwlhuzkcmychiltyzwzscdxbhpekdlmojaxdbhhphmwpxsnwqposumwbdcognawycvcefltmxqcukrraihtdvrgztuhivggxbkdgwxvtpxozqhzzoueklklgfuocaxbehfkdehztepsxwtymocybojiveyzexbkfixkmelhjabiyuinkmloavywbyvhwysbipnwtzdebgocbwpniadjxbhyaegwdaznpokkppptwdvzckokksvkteivjqtoqubfjnqadhtzmoaoaobngwxabfxmwramlduurmxutqvfhvwhjxusttuwzrixikluqfqhtndmeaulvsugprakkuhjmriueuqubhdvwgjagfndxklmbmzlgixuzhpfbhzfqccnknnqtdvsphhqvgdboaypipvlwwsnzualipebuz",
    "tjiazd"))
# print(Solution().minWindow_violent(*args))
# print(Solution().minWindow(*args))
# print(Solution().minWindow_noCounter(*args))
                 1] in wordDictCharsSet:  # 得到i, j后判断是否在Set之中,如果是则入栈,接着判断下面的
                stack += [(i, j)]
                i = j + 1
        return False

    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        dp = [True] + [False] * len(s)
        wordDict = set(wordDict)
        for i in range(len(s) + 1):
            for j in range(i):
                if dp[j] and s[j:i] in wordDict:
                    dp[i] = True
        return dp[len(s)]


speedtest((Solution().wordBreak, Solution().wordBreak_slow),
          ("leetcode", ["leet", "code"]))
speedtest((Solution().wordBreak, Solution().wordBreak_slow),
          ("applepenapple", ["apple", "pen"]))
speedtest((Solution().wordBreak, Solution().wordBreak_slow),
          ("catsandog", ["cats", "dog", "sand", "and", "cat"]))
speedtest((Solution().wordBreak, Solution().wordBreak_slow),
          ("goalspecial", ["go", "goal", "goals", "special"]))
speedtest((Solution().wordBreak, Solution().wordBreak_slow), (
    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
    [
        "a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa", "aaaaaaa", "aaaaaaaa",
        "aaaaaaaaa", "aaaaaaaaaa"
    ]))
speedtest((Solution().wordBreak, Solution().wordBreak_slow), (
    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    [
class Solution:
    def findBestValue(self, arr: List[int], target: int) -> int:
        if not arr:
            return 0
        arr.sort()
        sum = 0  # 保存arr[0,i)的和
        i = 0
        while i < len(arr):  # 用for会错过i==len(arr)的情况
            if sum + (len(arr) - i) * arr[i] > target:  # 如果把arr[i...]全变成arr[i]的和,大于target就结束
                break
            sum += arr[i]
            i += 1
        if i == len(arr):  # 如果target太大了,返回最后一个数字
            return arr[-1]
        if i == 0:  # 如果target太小了,所有数字都要变化。计算范围
            potentialResultRange = target // len(arr), target // len(arr) + 1
        else:  # 在arr[i-1]到arr[i]中都有可能
            potentialResultRange = [arr[i - 1], arr[i]]
        minDistance = 2 ** 31 - 1  # 与target最小差
        result = arr[-1]
        for potentialResult in range(potentialResultRange[0], potentialResultRange[1] + 1):  # arr[i-1]到arr[i]中挨个试一遍
            if abs((sum + (len(arr) - i) * potentialResult) - target) < minDistance:  # 刷新最好的结果
                minDistance = abs(sum + (len(arr) - i) * potentialResult - target)
                result = potentialResult
        return result


speedtest([Solution().findBestValue, lambda x, y: 3], ([4, 9, 3], 10))
speedtest([Solution().findBestValue, lambda x, y: 5], ([2, 3, 5], 10))
speedtest([Solution().findBestValue, lambda x, y: 11361], ([60864, 25176, 27249, 21296, 20204], 56803))
Esempio n. 5
0
                vaildSet.add((tpl[0], end))
            else:
                superSet = [
                    tpl for tpl in vaildSet if tpl[0] < begin and tpl[1] > end
                ]
                if not superSet:
                    vaildSet.add((begin, end))

        stackIndex = []
        vaildSet = set()
        for i, ch in enumerate(s):
            if ch == '(':
                stackIndex.append(i)
            elif ch == ')':
                if not stackIndex:
                    continue
                begin = stackIndex.pop()
                end = i + 1
                appendAndMerge(begin, end)
        vaildLength = [end - begin for begin, end in vaildSet]
        return max(vaildLength + [0])


speedtest((Solution().longestValidParentheses, lambda x: 0), ["("])
speedtest((Solution().longestValidParentheses, lambda x: 2), ["()(()"])
speedtest((Solution().longestValidParentheses, lambda x: 6), ["()(())"])
speedtest((Solution().longestValidParentheses, lambda x: 8), ["((()))())"])
speedtest((Solution().longestValidParentheses, lambda x: 128), [
    "))()())))(()()()()((()()(())))()()()()))()())))(()()()()((()()(())))())))()(())))()())))(()()()()((()()(())))()()()()(())))((()()))()()()()(())))((())()))()())))(()()()()((()()(())))()(())))()(())))()())))(()()()()((()()(())))()()()()(())))((()()))()()()()(())))((())()))()())))(()()()()((()()(())))()()()()(())))(()()()()(())))(()(()()()()(())))(((())))(())))()(())))()())))(()()()()((()()(())))()()()()(())))((()()))()()()()(())))((())()))()())))(()()()()((()()(())))()()()()(())))(()((())))()(())))()())))(()()()()((()()(())))()()()()(())))((()()))()()()()(())))((())()))()())))(()()()()((()()(())))()()()()(())))(()((((())(()())(()()()()((()()()(()()())()())))(()())()())))(()()()()((()()(())))()()()()(())))(()()()((()()(())))()()()()(())))(()((())))()()()()(())))(((((()))()())()()())()("
])
Esempio n. 6
0
                sets[adjNodeIdx].add(adjNode)
        return True

    def isBipartite(self, graph: List[List[int]]) -> bool:
        color = defaultdict(int)
        for node, adjNodes in enumerate(graph):
            if color[node] == 0:
                color[node] = 1
            for adjNode in adjNodes:
                if color[adjNode] == color[node]:
                    return False
                color[adjNode] = 1 if color[node] == 2 else 2
        return True


speedtest([Solution().isBipartite, lambda x: True],
          [[[1, 3], [0, 2], [1, 3], [0, 2]]])
speedtest([Solution().isBipartite, lambda x: False],
          [[[1, 2, 3], [0, 2], [0, 1, 3], [0, 2]]])
speedtest([Solution().isBipartite, lambda x: True],
          [[[4], [], [4], [], [0, 2, 3]]])
speedtest([Solution().isBipartite, lambda x: True],
          [[[1], [0], [4], [4], [2, 3]]])
speedtest([Solution().isBipartite, lambda x: True],
          [[[1], [0, 3], [3], [1, 2]]])
speedtest(
    [Solution().isBipartite, lambda x: False],
    [[[2, 4], [2, 3, 4], [0, 1], [1], [0, 1], [7], [9], [5], [], [6], [12, 14],
      [], [10], [], [10], [19], [18], [], [16], [15], [23], [23], [], [20, 21],
      [], [], [27], [26], [], [], [34], [33, 34], [], [31], [30, 31], [38, 39],
      [37, 38, 39], [36], [35, 36], [35, 36], [43], [], [], [40], [], [49],
      [47, 48, 49], [46, 48, 49], [46, 47, 49], [45, 46, 47, 48]]])
Esempio n. 7
0
                indexBegin += 1
                indexEnd -= 1
        return True

    def isSymmetric_fast(self, root: TreeNode) -> bool:
        def equals(node1: TreeNode, node2: TreeNode):
            if not node1 and not node2:
                return True
            elif (node1 and node2) is None:
                return False
            return node1.val == node2.val and equals(
                node1.left, node2.right) and equals(node1.right, node2.left)

        if not root:
            return True
        return equals(root.left, root.right)


speedtest([Solution().isSymmetric,
           Solution().isSymmetric_fast], [
               TreeUtil.createTreeByPreInOrder(
                   [1, 2, 4, 6, 5, 7, 9, 10, 8, 3, 5, 8, 7, 9, 10, 4, 6],
                   [4, 6, 2, 7, 10, 9, 5, 8, 1, 8, 5, 9, 10, 7, 3, 6, 4])
           ])
speedtest([Solution().isSymmetric,
           Solution().isSymmetric_fast], [
               TreeUtil.createTreeByPreInOrder(
                   [1, 2, 4, 6, 5, 7, 9, 10, 8, 2, 5, 8, 7, 9, 10, 4, 6],
                   [4, 6, 2, 7, 10, 9, 5, 8, 1, 8, 5, 9, 10, 7, 2, 6, 4])
           ])
Esempio n. 8
0
        array = np.zeros(limit抽到点数为止Exclusive + max卡牌点数)
        array[limit抽到点数为止Exclusive:limit爆点Inclusive + 1] = 1
        sums = array[limit抽到点数为止Exclusive + 1:limit抽到点数为止Exclusive +
                     max卡牌点数].sum()
        for i in range(limit抽到点数为止Exclusive - 1, -1, -1):
            array[i] = array[i + 1:i + max卡牌点数 + 1].sum() / max卡牌点数
        return array[0]

    def new21Game(self, N: int, K: int, W: int) -> float:
        limit爆点Inclusive, limit抽到点数为止Exclusive, max卡牌点数 = N, K, W
        array = np.zeros(limit抽到点数为止Exclusive + max卡牌点数)
        array[limit抽到点数为止Exclusive:limit爆点Inclusive + 1] = 1
        sums = array[limit抽到点数为止Exclusive + 1:limit抽到点数为止Exclusive +
                     max卡牌点数].sum()
        for i in range(limit抽到点数为止Exclusive - 1, -1, -1):
            sums += array[i + 1]
            array[i] = sums / max卡牌点数
            sums -= array[i + max卡牌点数]
        return array[0]


speedtest([Solution().new21Game, Solution().new21Game_slow], (10, 1, 10))
speedtest([Solution().new21Game, Solution().new21Game_slow], (6, 1, 10))
speedtest([Solution().new21Game, Solution().new21Game_slow], (21, 17, 10))
speedtest(
    [Solution().new21Game, Solution().new21Game_slow], (7467, 6303, 1576))
speedtest(
    [Solution().new21Game, Solution().new21Game_slow], (9811, 8776, 1096))
speedtest(
    [Solution().new21Game, Solution().new21Game_slow], (7467, 6303, 1576))
            dp(i - 1, j - 1, x + 1 if A[i] == B[j] else 0)
            dp(i, j - 1, 0), dp(i - 1, j, 0)

        maxAns = -2**31
        dp(len(A) - 1, len(B) - 1, 0)
        return maxAns

    def findLength(self, A: List[int], B: List[int]) -> int:
        dp = [[0] * (len(A) + 1) for _ in range(len(B) + 1)]
        result = 0
        for i in range(1, len(A) + 1):
            for j in range(1, len(B) + 1):
                if A[i - 1] == B[j - 1]:
                    dp[i][j] = dp[i - 1][j - 1] + 1
                    result = max(result, dp[i][j])
        return result


speedtest((Solution().findLength, Solution().findLength_recursive),
          ([5, 14, 53, 80, 48, 6, 7, 8], [6, 7, 8, 50, 47, 3, 80, 83]))
array1 = np.array(range(1000))
array2 = array1
speedtest((Solution().findLength, Solution().findLength_recursive),
          (array1, array2))
array1[:] = 59
array2 = array1.copy()
array1[3] = 91
array2[-1] = 94
speedtest((Solution().findLength, Solution().findLength_recursive),
          (array1, array2))
Esempio n. 10
0
from test_script import speedtest


class Solution:
    @lru_cache(maxsize=None)
    def jumpFloorIIRecursive(self, number: int):
        if number == 1:
            return 1
        sum = 0
        for i in range(1, number):
            sum += self.jumpFloorIIRecursive(number - i)
        return sum + 1

    def jumpFloorIISlow(self, n):
        dp = [1]
        for i in range(1, n):
            dp.append(sum(dp) + 1)
        return dp[-1]

    def jumpFloorII(self, n):
        dp = [1]
        sum = 0
        for i in range(1, n):
            sum += dp[i - 1]
            dp.append(sum + 1)
        return dp[-1]


speedtest((Solution().jumpFloorIIRecursive, Solution().jumpFloorIISlow,
           Solution().jumpFloorII), [50])
Esempio n. 11
0
            maxQueue = MaxQueue()
            yield None
        elif fun == 'push_back':
            yield maxQueue.push_back(value[0])
        elif fun == 'pop_front':
            yield maxQueue.pop_front()
        elif fun == 'max_value':
            yield maxQueue.max_value()
        else:
            raise ValueError


funs = ["MaxQueue", "push_back", "push_back", "max_value", "pop_front", "max_value"]
inputs = [[], [1], [2], [], [], []]
out = [None, None, None, 2, 1, 2]
speedtest([lambda f, arg: list(test(f, arg)), lambda x, y: out], [funs, inputs])
funs = ["MaxQueue", "pop_front", "max_value"]
inputs = [[], [], []]
out = [None, -1, -1]
speedtest([lambda f, arg: list(test(f, arg)), lambda x, y: out], [funs, inputs])
funs = ["MaxQueue", "max_value", "pop_front", "max_value", "push_back", "max_value", "pop_front", "max_value",
        "pop_front", "push_back", "pop_front", "pop_front", "pop_front", "push_back", "pop_front", "max_value",
        "pop_front", "max_value", "push_back", "push_back", "max_value", "push_back", "max_value", "max_value",
        "max_value", "push_back", "pop_front", "max_value", "push_back", "max_value", "max_value", "max_value",
        "pop_front", "push_back", "push_back", "push_back", "push_back", "pop_front", "pop_front", "max_value",
        "pop_front", "pop_front", "max_value", "push_back", "push_back", "pop_front", "push_back", "push_back",
        "push_back", "push_back", "pop_front", "max_value", "push_back", "max_value", "max_value", "pop_front",
        "max_value", "max_value", "max_value", "push_back", "pop_front", "push_back", "pop_front", "max_value",
        "max_value", "max_value", "push_back", "pop_front", "push_back", "push_back", "push_back", "pop_front",
        "max_value", "pop_front", "max_value", "max_value", "max_value", "pop_front", "push_back", "pop_front",
        "push_back", "push_back", "pop_front", "push_back", "pop_front", "push_back", "pop_front", "pop_front",
Esempio n. 12
0
        for future in futures:
            for sumOfdices in future:
                counter[sumOfdices] += future[sumOfdices]
        sumOfAll = sum(counter.values())
        retList = []
        for sumOfTime in sorted(counter.keys()):
            retList.append(counter[sumOfTime] / sumOfAll)
        return retList

    @lru_cache(maxsize=None)
    def getCountAt(self, dice数量: int, dices点数和: int) -> int:
        if dice数量 < 1 or dices点数和 < dice数量 or dices点数和 > dice数量 * 6:
            return 0
        if dice数量 == 1:
            return 1
        ret = [
            self.getCountAt(dice数量 - 1, dices点数和 - i) for i in range(6, 0, -1)
        ]
        return sum(ret)

    def twoSum(self, n: int) -> List[float]:
        dices点数和List = [
            self.getCountAt(n, sumOfdices)
            for sumOfdices in range(n, 6 * n + 1)
        ]
        dices点数和Sum = sum(dices点数和List)
        return [dicesSum / dices点数和Sum for dicesSum in dices点数和List]


speedtest([Solution().twoSum, Solution().twoSum_slow], [10])
                for i, existsPath in enumerate(paths):  # 如果存在路径与当前路径具有包含或者被包含的关系,则跳过或更新
                    existsPathSet = set(existsPath)
                    nowSet = set(path)
                    if existsPathSet.issubset(nowSet):
                        vaild = False
                        break
                    elif existsPathSet.issuperset(nowSet):
                        paths[i] = path
                        vaild = False
                        break
                if vaild:
                    paths.append(path)
        return paths


speedtest([Solution().findLadders, lambda x, y, z: [['a', 'c']]], ("a", "c", ["a", "b", "c"]))
speedtest([Solution().findLadders,
           lambda x, y, z: [['hit', 'hot', 'dot', 'dog', 'cog'], ['hit', 'hot', 'lot', 'log', 'cog']]],
          ("hit", "cog", ["hot", "dot", "dog", "lot", "log", "cog"]))
speedtest([Solution().findLadders, lambda x, y, z: []], ("hit", "cog", ["hot", "dot", "dog", "lot", "log"]))
speedtest([Solution().findLadders, lambda x, y, z: [["hot", "dot", "dog"], ["hot", "hog", "dog"]]],
          ("hot", "dog", ["hot", "cog", "dog", "tot", "hog", "hop", "pot", "dot"]))
speedtest([Solution().findLadders,
           lambda x, y, z: [["red", "ted", "tad", "tax"], ["red", "ted", "tex", "tax"], ["red", "rex", "tex", "tax"]]],
          ("red", "tax", ["ted", "tex", "red", "tax", "tad", "den", "rex", "pee"]))
speedtest([Solution().findLadders,
           lambda x, y, z: [["cat", "fat", "fit", "fin"], ["cat", "fat", "fan", "fin"], ["cat", "can", "fan", "fin"]]],
          ("cat", "fin",
           ["ion", "rev", "che", "ind", "lie", "wis", "oct", "ham", "jag", "ray", "nun", "ref", "wig", "jul", "ken",
            "mit", "eel", "paw", "per", "ola", "pat", "old", "maj", "ell", "irk", "ivy", "beg", "fan", "rap", "sun",
            "yak", "sat", "fit", "tom", "fin", "bug", "can", "hes", "col", "pep", "tug", "ump", "arc", "fee", "lee",
                for ALen in range(len(value) // 2 + 1):
                    A = value[:ALen]
                    # BDupStr = value[len(A):AStartIndexes[1]]
                    # if pattern.count('a') != 1:
                    #     BDupCount = self.findAll(pattern, 'a')[1] - self.findAll(pattern, 'a')[0] - 1
                    # else:
                    #     BDupCount = len(pattern) - 1
                    # B = BDupStr[:len(BDupStr) // BDupCount] if BDupCount else ''
                    for BLen in range(len(value) - ALen):
                        B = value[ALen:ALen + BLen]
                        if self.match(pattern, value, A, B):
                            return True
                return False


speedtest([Solution().patternMatching_offical,
           Solution().patternMatching], ("abba", "dogcatcatdog"))
speedtest([Solution().patternMatching_offical,
           Solution().patternMatching], ("abba", "dogcatcatfish"))
speedtest([Solution().patternMatching_offical,
           Solution().patternMatching], ("aaaa", "dogcatcatdog"))
speedtest([Solution().patternMatching_offical,
           Solution().patternMatching], ("abba", "dogdogdogdog"))
speedtest([Solution().patternMatching_offical,
           Solution().patternMatching], ("", "dogcatcatdog"))
speedtest([Solution().patternMatching_offical,
           Solution().patternMatching], ("b", "dogcatcatdog"))
speedtest([Solution().patternMatching_offical,
           Solution().patternMatching], ("ab", ""))
speedtest([Solution().patternMatching_offical,
           Solution().patternMatching], ("a", ""))
speedtest([Solution().patternMatching_offical,
from test_script import speedtest_format as speedtest


class Solution:
    def translateNum(self, num: int) -> int:
        def dp(i: int):
            nonlocal count
            if i >= len(numStr):
                count += 1
                return
            dp(i + 1)
            if i < len(numStr) - 1 and ('0' <= numStr[i] <= '1' or
                                        (numStr[i] == '2'
                                         and '0' <= numStr[i + 1] <= '5')):
                if numStr[i] != '0':  # 两位数不可以以0打头
                    dp(i + 2)

        numStr = str(num)
        count = 0
        dp(0)
        return count


speedtest([Solution().translateNum, lambda x: 2], [12])
speedtest([Solution().translateNum, lambda x: 1], [26])
speedtest([Solution().translateNum, lambda x: 1], [506])
speedtest([Solution().translateNum, lambda x: 1], [5006])
speedtest([Solution().translateNum, lambda x: 2], [50106])
speedtest([Solution().translateNum, lambda x: 2], [18580])
speedtest([Solution().translateNum, lambda x: 4], [185810])

class Solution:
    def findCircleNum(self, M: List[List[int]]) -> int:
        friendCircles: List[set] = []
        for i in range(len(M)):
            for j in range(i, len(M[0])):
                if M[i][j] == 1:
                    iCircleIndex = -1
                    for circleI, circleSet in enumerate(friendCircles):
                        if i in circleSet:
                            iCircleIndex = circleI
                    if iCircleIndex >= 0:
                        friendCircles[iCircleIndex].add(j)
                    else:
                        friendCircles.append({j})
        for i in range(len(friendCircles) - 2, -1, -1):
            for j in range(len(friendCircles) - 1, i, -1):
                if friendCircles[i].intersection(friendCircles[j]):
                    friendCircles[i] = friendCircles[i].union(friendCircles[j])
                    del friendCircles[j]
        return len(friendCircles)


speedtest([Solution().findCircleNum, lambda x: 2],
          [[[1, 1, 0], [1, 1, 0], [0, 0, 1]]])
speedtest([Solution().findCircleNum, lambda x: 1],
          [[[1, 1, 0], [1, 1, 1], [0, 1, 1]]])
speedtest([Solution().findCircleNum, lambda x: 1],
          [[[1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1], [1, 0, 1, 1]]])
Esempio n. 17
0
                valIs = root.val
            else:
                nowLength += 1
            longest = max(longest, nowLength)
            detectLongestPath(root.left, valIs + 1, nowLength)
            detectLongestPath(root.right, valIs + 1, nowLength)

        longest = 0
        if not root:
            return 0
        detectLongestPath(root, root.val, 0)
        return longest


speedtest(
    [Solution().longestConsecutive,
     Solution().longestConsecutive_clumsy],
    [TreeUtil.createTreeByPreInOrder([1, 3, 2, 4, 5], [1, 2, 3, 4, 5])])
speedtest(
    [Solution().longestConsecutive,
     Solution().longestConsecutive_clumsy],
    [TreeUtil.createTreeByPreInOrder([2, 3, 2, 1], [2, 1, 2, 3])])
root = TreeNode(1)
node = root
for i in range(2, 5001):
    node.right = TreeNode(i)
    node = node.right
speedtest(
    [Solution().longestConsecutive,
     Solution().longestConsecutive_clumsy], [root])
Esempio n. 18
0
        if not matrix:
            return False
        i, j = len(matrix) - 1, 0
        while i >= 0 and j < len(matrix[0]):
            if matrix[i][j] == target:
                return True
            elif matrix[i][j] > target:
                i -= 1
            elif matrix[i][j] < target:
                j += 1
        return False


speedtest([
    Solution().searchMatrix_multiBiSearch,
    Solution().searchMatrix,
    Solution().searchMatrix_extremelyFast
], ([[1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22],
     [10, 13, 14, 17, 24], [18, 21, 23, 26, 30]], 21))
speedtest([
    Solution().searchMatrix_multiBiSearch,
    Solution().searchMatrix,
    Solution().searchMatrix_extremelyFast
], ([[1, 4, 6, 8, 10, 12] + list(range(13, 1000)), [3, 5, 7, 8, 11, 13] +
     list(range(14, 1001)), [5, 6, 7, 9, 13, 15] + list(range(16, 1003)),
     [6, 9, 11, 12, 13, 16] + list(range(18, 1005))], 1004))
import numpy as np

matrix = np.zeros((5000, 5000))
for i in range(matrix.shape[0]):
    for j in range(matrix.shape[1]):
        matrix[i][j] = i + j
        result = []
        for i in range(len(nums)):
            result.append((multipliesList[i - 1] if i > 0 else 1) * (multipliesList[-1] // multipliesList[i]))
        return result

    def productExceptSelf_withoutMultiply(self, nums: List[int]) -> List[int]:
        if not nums:
            return []
        multiSum = 1
        leftMultipliesList = []
        rightMultipliesList = []
        for num in nums:
            multiSum *= num
            leftMultipliesList += [multiSum]
        multiSum = 1
        for num in reversed(nums):
            multiSum *= num
            rightMultipliesList += [multiSum]
        rightMultipliesList = rightMultipliesList[::-1]
        result = []
        for i in range(len(nums)):
            result += [
                (leftMultipliesList[i - 1] if i > 0 else 1) * (rightMultipliesList[i + 1] if i < len(nums) - 1 else 1)]
        return result


speedtest([Solution().productExceptSelf, Solution().productExceptSelf_withoutMultiply], [[0]])
speedtest([Solution().productExceptSelf, Solution().productExceptSelf_withoutMultiply], [[0, 0]])
speedtest([Solution().productExceptSelf, Solution().productExceptSelf_withoutMultiply], [[1, 2, 3, 4]])
speedtest([Solution().productExceptSelf, Solution().productExceptSelf_withoutMultiply], [list(range(10000))])