算法:附錄

這里面存放亂七八糟懶得分類石景、但都很有趣的算法題目劈猿,供自己把玩。這里懶得說人話潮孽,直接英文復(fù)制了揪荣。



Question 1:Contains Duplicate III
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
example1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
example2:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
explaination:
Maintain buckets each of size t+1 holding the last k elements. This is the invariant.
Buckets are [0, t], [t+1,2t+1], [2t+2, 3t+2],....
What are the conditions of a match? Either x lies in a bucket which already has a member (this directly means that x and this element are within t of each other). Or the two neighbors of around this bucket may have a potential match. Check the code for an explanation.
Lastly we notice how we purge elements from the cache/buckets which are stale i.e. outside the window of k elements.
Notice one more thing: -3//5 = -1 - Python does this automatically and hence we dont need any special magic for handling negative numbers.

maybe you will have this question:
In this code d[m] = nums[i],this will let d[m] always be last nums[i] since one key can only be one value. In abs(nums[i] - d[m - 1]) , why is that d[m-1] value not others in (m-1)th bucket.
The answer is:There will be at most 1 value in 1 bucket. If you have others in (m-1)th bucket, it must have already returned True when you find two values in the same (m-1)th bucket.

def containsNearbyAlmostDuplicate( nums: list, k: int, t: int) -> bool:
    if k < 1 or t < 0:
        return False
    cache = {}
    for i in range(len(nums)):
        if i - k > 0:
            bucket_id_to_delete = nums[i - k - 1] // (t + 1)
            del cache[bucket_id_to_delete]
        bucket_id = nums[i] // (t + 1)
        condition1 = (bucket_id in cache)
        condition2 = ((bucket_id - 1 in cache and abs(cache[bucket_id - 1] - nums[i]) <= t))
        condition3 = ((bucket_id + 1 in cache and abs(cache[bucket_id + 1] - nums[i]) <= t))
        if condition1 or condition2 or condition3:
            return True
        cache[bucket_id] = nums[i]
    return False

if __name__ == '__main__':
    nums = [1, 2, 3, 1]
    k = 3
    t = 0
    ans = containsNearbyAlmostDuplicate(nums,3,0)
    print(ans)


Question 2:01 Matrix
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.

Example 1: 
Input:     Output:
0 0 0      0 0 0
0 1 0      0 1 0
0 0 0      0 0 0

Example 2: 
Input:     Output:
0 0 0      0 0 0
0 1 0      0 1 0
1 1 1      1 2 1

Codes are as follows:

class Solution:
    def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
        q, m, n = [], len(matrix), len(matrix[0])
        for i in range(m):
            for j in range(n):
                if matrix[i][j] != 0:
                    matrix[i][j] = 0x7fffffff   ##其實大于10000就好了
                else:
                    q.append((i, j))
        while q:
            i,j = q.pop(0)
            for r, c in ((i, 1+j), (i, j-1), (i+1, j), (i-1, j)):
                z = matrix[i][j] + 1
                if 0 <= r < m and 0 <= c < n and matrix[r][c] > z:
                    matrix[r][c] = z
                    q.append((r, c))
        return matrix        

Question3:Valid Sudoku
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        return 1 == max(list(collections.Counter(
            x
            for i, row in enumerate(board)
            for j, c in enumerate(row)
            if c != '.'
            for x in ((c, i), (j, c), (i//3, j//3, c))
        ).values()) + [1])

Question4: Find Duplicate Subtrees
Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with same node values.

class Solution:
    def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]:
        def trv(root):
            if not root: return "null"
            struct = "%s,%s,%s" % (str(root.val), trv(root.left), trv(root.right))
            nodes[struct].append(root)
            return struct
        
        nodes = collections.defaultdict(list)
        trv(root)
        return [nodes[struct][0] for struct in nodes if len(nodes[struct]) > 1]

Question5:4Sum II
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.

Example:
Input:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]
Output:2
Explanation:
The two tuples are:
1.(0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2.(1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

class Solution:
    def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
        AB = collections.Counter(a+b for a in A for b in B)
        return sum(AB[-c-d] for c in C for d in D)

Question6:Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.

Example1:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

Example2:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        maxlen = 0
        hashmap = {}
        index = 0
        for idx,i in enumerate(s):
            if i in hashmap:
                #這里坑了我,當(dāng)時我寫的是 index = hashmap[i]+1往史,沒有考慮到此處該求 max
                index = max(hashmap[i]+1,index)   
            maxlen = max(maxlen, idx - index + 1)
            hashmap[i] = idx
        return maxlen

Question7



Question8




呃(⊙﹏⊙)仗颈,這篇文章我就不求贊了,椎例,挨决,知道對大家而言參考價值很小请祖,,脖祈,沒臉求贊肆捕,,盖高,福压,,或舞,

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市蒙幻,隨后出現(xiàn)的幾起案子映凳,更是在濱河造成了極大的恐慌,老刑警劉巖邮破,帶你破解...
    沈念sama閱讀 221,695評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件诈豌,死亡現(xiàn)場離奇詭異,居然都是意外死亡抒和,警方通過查閱死者的電腦和手機矫渔,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來摧莽,“玉大人庙洼,你說我怎么就攤上這事∧髟” “怎么了油够?”我有些...
    開封第一講書人閱讀 168,130評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長征懈。 經(jīng)常有香客問我石咬,道長,這世上最難降的妖魔是什么卖哎? 我笑而不...
    開封第一講書人閱讀 59,648評論 1 297
  • 正文 為了忘掉前任鬼悠,我火速辦了婚禮,結(jié)果婚禮上亏娜,老公的妹妹穿的比我還像新娘焕窝。我一直安慰自己,他們只是感情好照藻,可當(dāng)我...
    茶點故事閱讀 68,655評論 6 397
  • 文/花漫 我一把揭開白布袜啃。 她就那樣靜靜地躺著,像睡著了一般幸缕。 火紅的嫁衣襯著肌膚如雪群发。 梳的紋絲不亂的頭發(fā)上晰韵,一...
    開封第一講書人閱讀 52,268評論 1 309
  • 那天,我揣著相機與錄音熟妓,去河邊找鬼雪猪。 笑死,一個胖子當(dāng)著我的面吹牛起愈,可吹牛的內(nèi)容都是我干的只恨。 我是一名探鬼主播,決...
    沈念sama閱讀 40,835評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼抬虽,長吁一口氣:“原來是場噩夢啊……” “哼官觅!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起阐污,我...
    開封第一講書人閱讀 39,740評論 0 276
  • 序言:老撾萬榮一對情侶失蹤休涤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后笛辟,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體功氨,經(jīng)...
    沈念sama閱讀 46,286評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,375評論 3 340
  • 正文 我和宋清朗相戀三年手幢,在試婚紗的時候發(fā)現(xiàn)自己被綠了捷凄。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,505評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡围来,死狀恐怖跺涤,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情监透,我是刑警寧澤钦铁,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站才漆,受9級特大地震影響牛曹,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜醇滥,卻給世界環(huán)境...
    茶點故事閱讀 41,873評論 3 333
  • 文/蒙蒙 一黎比、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧鸳玩,春花似錦阅虫、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春购城,著一層夾襖步出監(jiān)牢的瞬間吕座,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評論 1 272
  • 我被黑心中介騙來泰國打工瘪板, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留吴趴,地道東北人。 一個月前我還...
    沈念sama閱讀 48,921評論 3 376
  • 正文 我出身青樓侮攀,卻偏偏與公主長得像锣枝,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子兰英,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,515評論 2 359