python練習(十三)

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

現在不止做簡單的了

Implement Queue using Stacks

題目

Implement the following operations of a queue using stacks.

push(x) – Push element x to the back of queue.
pop() – Removes the element from in front of queue.
peek() – Get the front element.
empty() – Return whether the queue is empty.
Notes:
You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

思路與解答

雖然還是簡單的,但是正是我不太想寫的那種

class MyQueue(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.l=[]

    def push(self, x):
        """
        Push element x to the back of queue.
        :type x: int
        :rtype: void
        """
        self.l.append(x)


    def pop(self):
        """
        Removes the element from in front of queue and returns that element.
        :rtype: int
        """
        a=self.l[0]
        del self.l[0]
        return a

    def peek(self):
        """
        Get the front element.
        :rtype: int
        """
        return self.l[0]

    def empty(self):
        """
        Returns whether the queue is empty.
        :rtype: bool
        """
        return len(self.l)==0

嗯,就這樣吧

答案

啊啊啊我根本沒審清題,光看見模擬隊列了
題目要求用堆棧模擬隊列。。。所以我沒有使用堆棧,蛋疼
不想再寫了,寫寫思路吧
用兩個堆棧模擬隊列。
一個負責push,一個負責pop
push時,將所有outStack的元素pop到inStack,然後inStack.append(push)
pop時,將所有inStack的元素pop到outStack,然後outStack.pop
peek時,將所有inStack的元素pop到outStack,然後outStack.peek
empty時,判斷兩個堆棧是否都爲空
貼一份別人的吧

class Queue(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.inStack, self.outStack = [], []

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.inStack.append(x)

    def pop(self):
        """
        :rtype: nothing
        """
        self.move()
        self.outStack.pop()

    def peek(self):
        """
        :rtype: int
        """
        self.move()
        return self.outStack[-1]

    def empty(self):
        """
        :rtype: bool
        """
        return (not self.inStack) and (not self.outStack) 

    def move(self):
        """
        :rtype nothing
        """
        if not self.outStack:
            while self.inStack:
                self.outStack.append(self.inStack.pop())

Longest Uncommon Subsequence I

題目

Given a group of two strings, you need to find the longest uncommon subsequence of this group of two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.

A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.

The input will be two strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn’t exist, return -1.

Example 1:
Input: “aba”, “cdc”
Output: 3
Explanation: The longest uncommon subsequence is “aba” (or “cdc”),
because “aba” is a subsequence of “aba”,
but not a subsequence of any other strings in the group of two strings.
Note:

Both strings’ lengths will not exceed 100.
Only letters from a ~ z will appear in input strings.

思路與解答

還是easy的
這題目的意思莫不是返回最長的那個?
然後它輸入了兩個一樣的。。。

class Solution(object):
    def findLUSlength(self, a, b):
        if a == b:return -1
        return len(a) if len(a)>len(b) else len(b)

這題目莫不是石樂志???
臥槽 0.77%

答案

       return -1 if a == b else max(len(a),len(b))

我好像又蠢了

討論區裏非常多的人認爲這是個 Stupid Question
他們思索了DP,DFS,BFS,LCS等各種方法

Combination Sum

題目

Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]

思路與解答

Medium難度的
這道題有些印象
好像是那道dfs超時使用list的那個(印象深刻)
。。。不太對,那個只是返回數量,這玩意還有隊列啊。
還用那個方案怕不是O(n^3)了啊
好像還是dfs好啊,因爲要同時生成不同的list
而且可以在類內定義變量

class Solution(object):
    def __init__(self):
        self.res=[]
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        def dfs(a, l, n):#a剩餘長度,l已生成列表,i防止掉頭,重複
            if a == 0:
                self.res.append(l)
                return
            for i in range(n, len(candidates)):
                if candidates[i] > a:
                    break
                dfs(a - candidates[i], l + [candidates[i]], i)

        dfs(target, [], 0)
        return self.res                              

a set of candidate numbers 是沒有重複,不是已排序,擦。

class Solution(object):
    def __init__(self):
        self.res=[]
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        def dfs(a, l, n):#a剩餘長度,l已生成列表,i防止掉頭,重複
            if a == 0:
                self.res.append(l)
                return
            for i in range(n, len(c)):
                if c[i] > a:
                    break
                dfs(a - c[i], l + [c[i]], i)
        c = sorted(candidates)        
        dfs(target, [], 0)
        return self.res         

答案

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        def dfs(remain, combo, index):
            if remain == 0:
                result.append(combo)
                return
            for i in range(index, len(candy)):
                if candy[i] > remain:
                    # exceeded the sum with candidate[i]
                    break #the for loop

                dfs(remain - candy[i], combo + [candy[i]], i)

        candy = sorted(candidates)
        result = []
        dfs(target, [], 0)
        return result

Subsets

題目

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

思路與解答

二重循環,修改第二重循環長度?

class Solution(object):
    def __init__(self):
        self.res=[]
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """

        def dfs(l,n):#l , n長度
            self.res.append(l)
            if n == len(nums)-1:
                return
            for i in range(n+1,len(nums)):
                dfs(l+[nums[i]],i)
        dfs([],-1)
        return self.res
#[[],[1],[1,2],[1,2,3],[1,3],[2],[2,3],[3]]

和上一題有一點點相似
8%,擦 76ms

答案

def subsets(self, S):#56ms
    if not S:
        return [[]]
    else:
        S.sort()
        pre_subsets = self.subsets(S[1:])
        #print pre_subsets,S
        #print pre_subsets + [[S[0]]+elem for elem in pre_subsets]
        return pre_subsets + [[S[0]]+elem for elem in pre_subsets]

#[[],[3],[2],[2,3],[1],[1,3],[1,2],[1,2,3]]
'''
[[]] [3]
[[], [3]]
[[], [3]] [2, 3]
[[], [3], [2], [2, 3]]
[[], [3], [2], [2, 3]] [1, 2, 3]
[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
'''

我說我怎麼搜不到subsets這個函數,才注意到是本身
我的是從前往後的,這個是從後往前的

def subsets(self, nums):#49ms  只能猜個大概
    return reduce(lambda L, ele: L + [l + [ele] for l in L], nums, [[]])
#[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

def subsets(self, nums):#52ms product函數...
    [[x for x in l if x is not None] for l in itertools.product(*zip(nums, [None] * len(nums)))]
#[[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]]

def subsets(self, nums): #52ms combinations
    [l for n in range(len(nums) + 1) for l in itertools.combinations(nums, n)]
#[[],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]
class Solution: #62ms
    def subsets(self, S):
        # Base result
        result = [[]]
        for num in S:
            #print num,result
            for element in result[:]:
                x=element[:]
                #print x,num
                x.append(num)
                result.append(x)
        return result

#[[],[1],[1,2],[1,2,3],[1,3],[2],[2,3],[3]]
'''
1 [[]]
[] 1
2 [[], [1]]
[] 2
[1] 2
3 [[], [1], [2], [1, 2]]
[] 3
[1] 3
[2] 3
[1, 2] 3
'''

終於見到一個和我輸出順序一樣的了

# DFS recursively 48ms
def subsets1(self, nums):
    res = []
    self.dfs(sorted(nums), 0, [], res)
    return res

def dfs(self, nums, index, path, res):
    res.append(path)
    for i in xrange(index, len(nums)):
        self.dfs(nums, i+1, path+[nums[i]], res)
#[[],[1],[1,2],[1,2,3],[1,3],[2],[2,3],[3]]  又一個,但是比我快那麼多
# Bit Manipulation    #46ms 不愧是位操作,就是快
def subsets2(self, nums):
    res = []
    nums.sort()
    for i in xrange(1<<len(nums)):
        tmp = []
        for j in xrange(len(nums)):
            if i & 1 << j:  # if i >> j & 1:
                tmp.append(nums[j])
        res.append(tmp)
    return res
#[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] 

# Iteratively #52ms
def subsets(self, nums):
    res = [[]]
    for num in sorted(nums):
        res += [item+[num] for item in res]
    return res
#[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
#好像是上邊某個的簡化版

我還能怎樣,能怎樣….

Word Ladder II

這個是hard難度的,看了看題,看起來還可以用dfs來做,不過估計會相當慢,還是先做medium難度的吧

Binary Tree Level Order Traversal

題目

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
return its level order traversal as:
[
  [3],
  [9,20],
  [15,7]
]

思路與解答

dfs應該能做,只要在dfs中添加tree的層數即可,但是怎麼確定tree一共有幾層來確定初始List的長度呢,應該是不能的
不過好像bfs要好些啊(bfs怎麼寫啊,摔)

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def __init__(self):
        self.res=[]
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        def dfs(tree,n):
            if tree.left or tree.right:
                if len(self.res) < n+1:
                    self.res += [[]]
                if tree.left:
                    self.res[n] += [tree.left.val]
                    dfs(tree.left,n+1)
                if tree.right:
                    self.res[n] += [tree.right.val]
                    dfs(tree.right,n+1)
        if root:  
            self.res += [[root.val]]
            dfs(root,1)
        return self.res

還是用的dfs,42ms,90%,哦哦

答案

#Solution 1, (6 lines)
def levelOrder(self, root):
    ans, level = [], [root]
    while root and level:
        ans.append([node.val for node in level])
        LRpair = [(node.left, node.right) for node in level]
        level = [leaf for LR in LRpair for leaf in LR if leaf]
    return ans

#Solution 2, (5 lines), same idea but use only one list comprehension in while loop to get the next level
def levelOrder(self, root):
    ans, level = [], [root]
    while root and level:
        ans.append([node.val for node in level])            
        level = [kid for n in level for kid in (n.left, n.right) if kid]
    return ans

#Solution 3 (10 lines), just an expansion of solution 1&2 for better understanding.
def levelOrder(self, root):
    if not root:
        return []
    ans, level = [], [root]
    while level:
        ans.append([node.val for node in level])
        temp = []
        for node in level:
            temp.extend([node.left, node.right])
        level = [leaf for leaf in temp if leaf]
    return ans

bfs應該這麼寫

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