python學習(十八)

注意,答案只是代表是他人寫的代碼,正確,但不一定能通過測試(比如超時),列舉出來只是它們擁有着獨到之處,雖然大部分確實比我的好

168. Excel Sheet Column Title

題目

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB 

思路與解答

這題我做過啊。。。好像那個是反向的。。。

        s = ""
        while True:
            s = chr(65+(n-1)%26) + s
            if n <= 26: return s
            n = (n-1)/26

當時爲了理清邏輯想了好久,(n-1)%26和(n-1)/26分別都是錯了一次才反應過來
想想怎麼化簡

        s = ""
        while n > 0:
            s,n = chr(65+(n-1)%26) + s,(n-1)/26   
        return s

答案

從10個數字轉換爲26個數字。這個棘手的部分是在26進制系統中缺少等價數字’0’。這個說法很好,使我更清楚的理解這道題

def convertToTitle(self, n):
    r = ''
    while(n>0):
        n -= 1
        r = chr(n%26+65) + r
        n /= 26
    return r

其它人的方案

    def convertToTitle(self, num):
        capitals = [chr(x) for x in range(ord('A'), ord('Z')+1)]
        result = []
        while num > 0:
            result.append(capitals[(num-1)%26])
            num = (num-1) // 26
        result.reverse()
        return ''.join(result)

一行方案,又是巧妙的遞歸調用自己

return "" if num == 0 else self.convertToTitle((num - 1) / 26) + chr((num - 1) % 26 + ord('A'))

501. Find Mode in Binary Search Tree

題目

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than or equal to the node’s key.
The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
Both the left and right subtrees must also be binary search trees.
For example:
Given BST [1,null,2,2],

   1
    \
     2
    /
   2

return [2].

Note: If a tree has more than one mode, you can return them in any order.

Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).

思路與解答

創個全局變量字典用來保存個數?遍歷用來統計?
居然可能有多個

from collections import defaultdict 
class Solution(object):
    d=defaultdict(int) 

    def findMode(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """

        def dfs(r):
            if not r: return
            self.d[r.val] += 1
            dfs(r.left)
            dfs(r.right)
        dfs(root)
        vmax = vmax = sorted(self.d.items(), lambda x, y: cmp(x[1], y[1]), reverse=True)[0][1]  
        return [k for k in self.d.keys() if self.d[k] == vmax]

這裏寫圖片描述
這裏寫圖片描述
經過我不斷的嘗試,發現這道題在測試的時候怎麼說呢,根本沒有間隔,由於我的字典沒有辦法連續使用,所以產生了GG
於是我在方法開頭用d={}重置了字典,結果發現沒有defaultdict(int) 效果了,心一橫,乾脆不用了

class Solution(object):
    def findMode(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root :return []
        d={}
        def dfs(r):
            if not r: return
            d[r.val] = d.get(r.val,0)+1
            dfs(r.left)
            dfs(r.right)
        dfs(root)
        vmax = sorted(d.items(), lambda x, y: cmp(x[1], y[1]), reverse=True)[0][1]     
        return [k for k in d.keys() if d[k] == vmax]

至於O(1)的方案?emmmmmm

答案

counter…

count = collections.Counter()

def dfs(node):
if node:
count[node.val] += 1
dfs(node.left)
dfs(node.right)

dfs(root)
max_ct = max(count.itervalues())
return [k for k, v in count.iteritems() if v == max_ct]
Do

dalao的O(1)方案自己過去拜讀吧

28. Implement strStr()

題目

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

思路與解答

題目在說什麼啊???
好像是兩個字符串,尋找一個在另一箇中的匹配,返回首字母位置

        if needle not in haystack:return -1
        for i in range(len(haystack) - len(needle)+1):
            if haystack[i:i+len(needle)] == needle:
                return i

答案

不需要前面那個判斷啊

    for i in range(len(haystack) - len(needle)+1):
        if haystack[i:i+len(needle)] == needle:
            return i
    return -1

emmm

def strStr(self, haystack, needle):
    if needle == "":
        return 0
    for i in range(len(haystack)-len(needle)+1):
        for j in range(len(needle)):
            if haystack[i+j] != needle[j]:
                break
            if j == len(needle)-1:
                return i
    return -1

661. Image Smoother

題目

Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.

Example 1:

Input:
[[1,1,1],
[1,0,1],
[1,1,1]]
Output:
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]

Explanation:
For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0
Note:
The value in the given matrix is in the range of [0, 255].
The length and width of the given matrix are in the range of [1, 150].

思路與解答

這題讀一遍,好像懂了,又好像沒懂,不到1的都捨棄了?
感覺寫起來會很麻煩啊
啊啊啊啊啊
看到別人的答案後更不想繼續寫下去了

答案

        N = [[0]*len(M[0]) for i in range(len(M))]
        M.insert(0,[-1]*(len(M[0])+2))
        M.append([-1]*len(M[0]))
        for i in range(1,len(M)-1):
            M[i].insert(0,-1)
            M[i].append(-1)
        for i in range(1,len(M)-1):
            for j in range(1,len(M[0])-1):
                count = 0
                Sum = 0
                for k in range(-1,2):
                    for l in range(-1,2):
                        if M[i+k][j+l] != -1:
                            count += 1
                            Sum += M[i+k][j+l]
                N[i-1][j-1] = int(Sum/count)
        return N

500. Keyboard Row

題目

Given a List of words, return the words that can be typed using letters of alphabet on only one row’s of American keyboard like the image below.

思路與解答

感覺上也是非常簡單的
生成基礎的字典感覺就好麻煩啊

class Solution(object):
    def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        ls = ["QWERTYUIOPqwertyuiop", "ASDFGHJKLasdfghjkl", "ZXCVBNMzxcvbnm" ]
        dq,da,dz={},{},{}
        for s in ls[0]:
            dq[s] = s
        for s in ls[1]:
            da[s] = s
        for s in ls[2]:
            dz[s] = s
        l=[]
        for w in words:
            f,nf=0,0
            for s in w:
                if s in dq:nf=1
                if s in da:nf=2
                if s in dz:nf=3
                if f != 0 and f != nf:
                    break
                else:
                    f = nf
            else:
                l.append(w)
        return l

雖然看起來長,但是運行起來還是蠻快的
for循環那裏應該還能優化的,可是怎麼改呢

答案

6666,set還能這樣用

        return [word for row in [set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')] for word in words if set(word.lower()) <= row]

row1 = set("qwertyuiopQWERTYUIOP")
row2 = set("asdfghjklASDFGHJKL")
row3 = set("ZXCVBNMzxcvbnm")
return filter(lambda x: set(x).issubset(row1) or set(x).issubset(row2) or set(x).issubset(row3), words)

咳咳,這是啥?是正則匹配?厲害了

return filter(re.compile('(?i)([qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*)$').match, words)

all函數?話說那三個all條件能放一行的吧

result = []
        r1 = str('qwertyuiopQWERTYUIOP')
        r2 = str('asdfghjklASDFGHJKL')
        r3 = str('zxcvbnmZXCVBNM')
        for item in words:
            if all((letter in r1) for letter in item):
                result.append(item)
            elif all((letter in r2) for letter in item):
                result.append(item)
            elif all((letter in r3) for letter in item):
                result.append(item)
        return result

反而沒見到誰用字典了。。。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章