leetcode簡單(141-160)python
606. Construct String from Binary Tree(e-141)---------
You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.
617. Merge Two Binary Trees(e-142)------------
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
622. Design Circular Queue(e-143)-------------
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called ‘Ring Buffer’.
One of the Benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we can not insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.
Your implementation should support following operations:
- MyCircularQueue(k): Constructor, set the size of the queue to be k.
- Front: Get the front item from the queue. If the queue is empty, return -1.
- Rear: Get the last item from the queue. If the queue is empty, return -1.
- enQueue(value): Insert an element into the circular queue. Return true if the operation is successful.
- deQueue(): Delete an element from the circular queue. Return true if the operation is successful.
- isEmpty(): Checks whether the circular queue is empty or not.
- isFull(): Checks whether the circular queue is full or not.
628. Maximum Product of Three Numbers(e-144)
Given an integer array, find three numbers whose product is maximum and output the maximum product.
class Solution(object):
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
snum=sorted(nums)
if snum[0]<0 and snum[1]<0 and snum[-1]>0:
a=snum[0]*snum[1]*snum[-1]
b=snum[-1]*snum[-2]*snum[-3]
return max(a,b)
else:
return snum[-1]*snum[-2]*snum[-3]
633. Sum of Square Numbers(e-145)
Given a non-negative integer c
, your task is to decide whether there're two integers a
and b
such that a2 + b2 = c.
class Solution(object):
def judgeSquareSum(self, c):
"""
:type c: int
:rtype: bool
"""
n = int(c ** 0.5)
start = 0
end = n
while start <= end:
mid = start ** 2 + end ** 2
if mid == c:
return True
elif mid < c:
start += 1
else:
end -= 1
return False
637. Average of Levels in Binary Tree(e-146)-----------
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
641. Design Circular Deque(e-147)--------
Design your implementation of the circular double-ended queue (deque).
Your implementation should support following operations:
- MyCircularDeque(k): Constructor, set the size of the deque to be k.
- insertFront(): Adds an item at the front of Deque. Return true if the operation is successful.
- insertLast(): Adds an item at the rear of Deque. Return true if the operation is successful.
- deleteFront(): Deletes an item from the front of Deque. Return true if the operation is successful.
- deleteLast(): Deletes an item from the rear of Deque. Return true if the operation is successful.
- getFront(): Gets the front item from the Deque. If the deque is empty, return -1.
- getRear(): Gets the last item from Deque. If the deque is empty, return -1.
- isEmpty(): Checks whether Deque is empty or not.
- isFull(): Checks whether Deque is full or not.
643. Maximum Average Subarray I(e-148)
Given an array consisting of n
integers, find the contiguous subarray of given length k
that has the maximum average value. And you need to output the maximum average value.
class Solution(object):
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
res = sum(nums[0:k])
tmp = res
n = len(nums)
for i in range(k,n):
tmp = tmp - nums[i -k] + nums[i]
res = max(res, tmp)
return res / ( k + 0.0)
645. Set Mismatch(e-149)
The set S
originally contains numbers from 1 to n
. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.
Given an array nums
representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.
class Solution:
def findErrorNums(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
dict1 = {}
result = []
for i in range(len(nums)):
if nums[i] not in dict1:
dict1[nums[i]] = nums[i]
else:
result.append(nums[i])
for i in range(len(nums)):
if i + 1 not in dict1:
result.append(i+1)
return result
653. Two Sum IV - Input is a BST(e-150)---------
Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.
657. Robot Return to Origin(e-151)
There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.
The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.
Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.
class Solution(object):
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
x=0
y=0
for s in moves:
if s=="L":
x-=1
elif s=="R":
x+=1
elif s=="U":
y+=1
elif s=="D":
y-=1
if x==0 and y==0:
return True
else:
return False
661. Image Smoother(e-152)
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.
class Solution(object):
def imageSmoother(self, M):
"""
:type M: List[List[int]]
:rtype: List[List[int]]
"""
m = len(M)
n = len(M[0])
ans = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
cnt = 0
sums = 0
for di in range(-1, 2):
for dj in range(-1, 2):
newi, newj = i + di, j + dj
if 0 <= newi < m and 0 <= newj < n:
cnt += 1
sums += M[newi][newj]
ans[i][j] = sums / cnt
return ans
665. Non-decreasing Array(e-153)
Given an array with n
integers, your task is to check if it could become non-decreasing by modifying at most 1
element.
We define an array is non-decreasing if array[i] <= array[i + 1]
holds for every i
(1 <= i < n).
class Solution(object):
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
one, two = nums[:], nums[:]
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
one[i] = nums[i + 1]
two[i + 1] = nums[i]
break
return one == sorted(one) or two == sorted(two)
669. Trim a Binary Search Tree(e-154)-----------------
Given a binary search tree and the lowest and highest boundaries as L
and R
, trim the tree so that all its elements lies in [L, R]
(R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.
671. Second Minimum Node In a Binary Tree(e-155)----------
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two
or zero
sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.
If no such second minimum value exists, output -1 instead.
674. Longest Continuous Increasing Subsequence(e-156)
Given an unsorted array of integers, find the length of longest continuous
increasing subsequence (subarray).
class Solution(object):
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n=len(nums)
if n<=1:
return n
res=0
length=1
for i in range(n-1):
if nums[i]<nums[i+1]:
length+=1
else:
res=max(length, res)
length=1
res=max(length, res)
return res
680. Valid Palindrome II(e-157)
Given a non-empty string s
, you may delete at most one character. Judge whether you can make it a palindrome.
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s)<2:
return True
count=0
i=0
j=len(s)-1
while i<j:
if s[i]!=s[j]:
i+=1
count+=1
else:
i+=1
j-=1
if count<2:
return True
count=0
i=0
j=len(s)-1
while i<j:
if s[i]!=s[j]:
j-=1
count+=1
else:
i+=1
j-=1
if count<2:
return True
return False
682. Baseball Game(e-158)
You're now a baseball game point recorder.
Given a list of strings, each string can be one of the 4 following types:
Integer
(one round's score): Directly represents the number of points you get in this round."+"
(one round's score): Represents that the points you get in this round are the sum of the last twovalid
round's points."D"
(one round's score): Represents that the points you get in this round are the doubled data of the lastvalid
round's points."C"
(an operation, which isn't a round's score): Represents the lastvalid
round's points you get were invalid and should be removed.
Each round's operation is permanent and could have an impact on the round before and the round after.
You need to return the sum of the points you could get in all the rounds
class Solution(object):
def calPoints(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
point_list=[]
for op in ops:
if op=="C":
if point_list:
del point_list[-1]
elif op=="D":
if point_list:
point_list.append(point_list[-1]*2)
elif op=="+":
point_list.append(sum(point_list[-2:]))
else:
point_list.append(int(op))
return sum(point_list)
686. Repeated String Match(e-159)
Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1.
For example, with A = "abcd" and B = "cdabcdab".
Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A repeated two times ("abcdabcd").
Note:
The length of A
and B
will be between 1 and 10000.
class Solution(object):
def repeatedStringMatch(self, A, B):
"""
:type A: str
:type B: str
:rtype: int
"""
sa, sb = len(A), len(B)
x = 1
while (x - 1) * sa <= 2 * max(sa, sb):
if B in A * x:
return x
x += 1
return -1
687. Longest Univalue Path(e-160)--------
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
Note: The length of path between two nodes is represented by the number of edges between them.