Leetcode刷题记录_20181101

257. Binary Tree Paths 

深度优先遍历

 1 class Solution:
 2     def binaryTreePaths(self, root):
 3         """
 4         :type root: TreeNode
 5         :rtype: List[str]
 6         """
 7         res, path_list = [],[]
 8         self.addleaf(root,path_list,res)
 9         return res
10         
11         
12     def addleaf(self,root,path_list,res):
13         if not root:
14             return 
15         path_list.append(str(root.val))
16         if not root.left and not root.right:
17             res.append('->'.join(path_list))
18         if root.left:
19             self.addleaf(root.left,path_list,res)
20         if root.right:
21             self.addleaf(root.right,path_list,res)
22         path_list.pop()
View Code

278. First Bad Version 

二分法

 1 class Solution:
 2     def firstBadVersion(self, n):
 3         """
 4         :type n: int
 5         :rtype: int
 6         """
 7         if n ==0:
 8             return None
 9         left = 1
10         right = n
11         if isBadVersion(1):
12             return 1
13         if not isBadVersion(n):
14             return None
15         while abs(left-right) !=1:
16             mid = int(0.5*(left+right))
17             if isBadVersion(mid):
18                 right = mid
19             if not isBadVersion(mid):
20                 left = mid
21         return left+1
View Code

283. Move Zeroes

 1 class Solution:
 2     def moveZeroes(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: void Do not return anything, modify nums in-place instead.
 6         """
 7         if not nums:
 8             return None
 9         m = nums.count(0)
10         if m != 0:
11             j = 0
12             for i in nums:
13                 if i != 0:
14                     nums[j] = i
15                     j +=1
16             nums[len(nums)-m:] = [0]*m
View Code

290. Word Pattern 

zip+set

 1 class Solution:
 2     def wordPattern(self, pattern, str):
 3         """
 4         :type pattern: str
 5         :type str: str
 6         :rtype: bool
 7         """
 8         s = str.split(' ')
 9         if  len(s) == len(pattern):   
10             return len(set(pattern)) == len(set(s)) == len(set(zip(pattern,s)))
11         else:
12             return False
View Code

猜你喜欢

转载自www.cnblogs.com/autoyzz/p/9891255.html
今日推荐