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应该这么写

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值