The next week ... Brush another week, this week obviously feel more smooth brush, refueling .... Pascal ' s triangle
English Description: Given numrows, generate the numrows of Pascal ' s triangle.
Example:
For example, given numrows = 5,
return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
Given a particular row, returns a column of Yang Hui's triangles
Solution:
def generate (self, numrows): ""
: Type Numrows:int
: rtype:list[list[int] "" "
triangle = []
for row_num in range (numrows):
row = [None for _ in range (row_num+1)]
row[0], row[-1] = 1, 1 for
J in Range (1, Len (row)-1):
row[j] = triangle[row_num-1][j-1] + triangle[row_num-1][j]
triangle.append (ROW) return
Triangle
Parsing: Using the nature of the Yang Hui's triangle, the current line as to the value of the previous line about Pascal's triangle II
English Description: Given a index k, return the kth row of the Pascal ' s triangle.
Example:
For example, given k = 3, return
[1,3,3,1].
Note:
could your optimize your algorithm to use only O (k) extra spaces?
Return to the Yang Hui's triangle of the K line elements, is the Yang Hui's triangle of the advanced
Solution:
def getRow (self, RowIndex): ""
: Type Rowindex:int
: Rtype:list[int] ""
"
row = [1] for
_ in Range (RowIndex):
row = [x + y for x, y in Zip ([0] + row, row+[0])] return
row
Parsing: Just use a list to save the value of the current row. Best time to buy and Sell the stock
English Description: Say you have an array for which the ith element are the price of a given-the- Complete at most one transaction (ie, buy one and sell one share of the "stock"), design a algorithm to find the maximum P Rofit.
Example:
Example 1:
Input: [7, 1, 5, 3, 6, 4]
output:5
max. difference = 6-1 = 5 (Not 7-1 = 6, as selling price needs To is larger than buying price
Example 2:
Input: [7, 6, 4, 3, 1] output:0 in-case
, no transaction i s done, i.e max Profit = 0.
If you have a list of stock returns, you can only buy and sell it once and get the maximum benefit
Solution:
def maxprofit (self, prices): ""
: Type Prices:list[int]: Rtype:int "" "
minprice = 9999999
Maxpro = 0 for
i in range (len (prices)):
if prices[i] < minprice:
minprice = prices[i]
else:
if prices[i]-minprice > Maxpro:
maxpro = prices[i]-Minprice return
Maxpro
Parsing: Using two variables to record the minimum value of the current day and the maximum value of the gains best time to buy and Sell stock II
English Description: Say you have an array for which the ith element are the price of a given-the-a-day i.design-A-find th E maximum profit. You may complete as many transactions as (ie, buy one and sell one share of the stock multiple times). However, you could not engage in multiple transactions at the same time (ie, your must sell the stock before your buy again).
In the first question of the advanced, that is, you can operate the sale of countless times to obtain the maximum value of income
Solution:
def maxprofit (self, prices): ""
: Type Prices:list[int]
: Rtype:int "" "Return
sum (max (prices[i +1]-prices[i], 0 for I in range (len (prices)-1))
Analysis: Buy and sell once a day, the benefit is plus, otherwise add 0 Valid palindrome
English Description: Given A string, determine if it is a palindrome, considering only alphanumeric characters and ignoring.
Example:
For example,
"A mans, a plan, a Canal:panama" is a palindrome.
" Race a car ' is not a palindrome.
Note:
Have your consider that the string might is empty? This is a good question to ask during a interview.
For the purpose of this problem, we define empty string as valid palindrome.
For a given string, regardless of space, punctuation, case, is not a palindrome
Solution:
def ispalindrome (self, s): ""
: Type s:str
: Rtype:bool
""
If Len (s) = 0: return
True
Import re Result
= Re.findall ("[a-za-z0-9]+", s) result
= "". Join (Result). Lower () to
I in range (Len ( Result)//2):
if result[i]!= result[-(i+1)]: return
False return
True
Parsing: Using a regular matching string in the letter. And then determine if this string is a palindrome
English Description: Given an array of integers, every element appears twice for one. Find is single one.
Note:
Your algorithm should have a linear runtime. Could you implement it without using extra memory?
Use O (n) time complexity, O (1) space complexity, find the list is not only one occurrence of the value, the others appear up to two times
Solution:
def singlenumber (self, Nums): ""
: Type Nums:list[int]: Rtype:int "" "
s_nums = sorted (nums) For
i in range (0,len (s_nums) -1,2):
if s_nums[i]!= s_nums[i+1]: return
s_nums[i] return
s_nums[-1]
Parsing: Sort the list, and then traverse the step length to 2 linked list Cycle
English Description: Given A linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra?
Use O (1) space complexity to determine whether the linked list has a ring
Solution:
def hascycle (self, head): ""
: Type Head:listnode
: Rtype:bool
""
slow = fast =
Head while Fast and Fast.next:
slow = slow.next
fast = Fast.next.next
if slow = = Fast: return
True
Analysis: Use speed "pointer" Min Stack
English Description: Design a stack that supports push, POPs, top, and retrieving the minimum element in constant time.
Push (x)--push element x onto stack.
Pop ()--Removes the element on top of the stack.
Top ()-Get the top element.
Getmin ()--Retrieve The minimum element in the stack.
Example:
Minstack minstack = new Minstack ();
Minstack.push ( -2);
Minstack.push (0);
Minstack.push ( -3);
Minstack.getmin (); --> Returns-3.
Minstack.pop ();
Minstack.top (); --> Returns 0.
Minstack.getmin (); --> Returns-2.
Chinese Description: Design a stack
Solution:
Class Minstack (object):
def __init__ (self): "" "
Initialize your data structure here.
" " Self.value = []
def push (self, X): ""
: Type x:int
: rtype:void
""
self.value.append ( x
def pop (self): ""
: Rtype:void "" "
Self.value.pop () def top
(self):
" "
: Rtype:int
"" Return
Self.value[-1]
def getmin (self): ""
: Rtype:int
"" " return
min (self.value)
Parsing: Using Python's list to simulate stack intersection of two linked Lists
English Description: Write a program "to find" node at which the intersection of two singly linked lists.
Example:
For example, the following two linked lists:
A: a1→a2 ↘ c1→c2→c3 ↗
B: b1→b2→b3
B Egin to intersect at node C1.
Chinese Description: Find two public nodes of a linked list
Solution:
def getintersectionnode (self, Heada, headb): "" ": Type Head1, Head1:ListNode:rtype:ListNode ' "' If Heada is ' None or headb is None:return None Lcura = Heada La = 0 W
Hile Lcura:la + = 1 Lcura = lcura.next lb = 0 lcurb = headb while lcurb: LB + 1 lcurb = Lcurb.next if la > lb:cha = la-lb cura = Head
A while cha!= 0:cura = cura.next Cha-= 1 curb = headb
if cura = = Curb:return Cura while cura!= Curb:cura = Cura.next curb = Curb.next if cura = = Curb:return Cura return None E Lif La < Lb:cha = Lb-la curb = headb while cha!= 0:curb = Curb . Next CHA-= 1 cura = Heada if cura = Curb:return cura while Cura!= Curb: Cura = Cura.next Curb = Curb.next if cura = Curb:retu RN Curb return None Else:cura = Heada curb = headb while cura!=
Curb:cura = Cura.next Curb = Curb.next if cura = Curb:
return cura if cura = = Curb:return Cura return None
Parsing: Long list first go two list length difference step, then together walk two Sum ii-input array is sorted
English Description: Given an array of integers it already sorted in ascending order, find two numbers such that they add up to a SPE Cific target number.
The function twosum should return indices of the two numbers such this they add up to the target where index1 must is Les S than Index2. Please note this your returned answers (both INDEX1 and index2) are not zero-based.
You may assume the solution element same of each input would have exactly one twice and.
Example:
Input:numbers={2, 7, one, target=9,
output:index1=1, index2=2
Description: Find two worthwhile and equal target values in a list, and return the index
Solution:
def twosum (self, Numbers, target): ""
: Type Numbers:list[int]
: Type Target:int
: Rtype:list[int] "" "
i = 0
j =-1 while
I <= (len (Numbers)) and ABS (j) <= (len (Numbers)):
if numbers[i] + number S[J] < target:
i + 1
elif numbers[i] + numbers[j] > target:
J-= 1
else: return
[I+1, Len (n Umbers) + j+1] return
[]
Parsing: Directly from front to back, compare the ordered array Excel Sheet Column Title
English Description: Given a positive integer, return it corresponding column title as appear in an Excel sheet.
Example:
1-> A
2-> B
3-> C
...
-> Z
-> AA
Given an integral type, return the corresponding letter
Solution:
def converttotitle (self, N): ""
: Type n:int
: rtype:str "" Result
= [] while
n > 0:
Result.append (string.ascii_uppercase[(n-1)%])
n = (n-1)//num return
"". Join (Reversed (result))
Resolution: Emmmm ... this problem I will not,,, now do not understand,,, majority Element
English Description: Given an array of size n, find the majority element. The majority element is the element this appears more than⌊n/2⌋times.
You may assume this array is non-empty and the majority element always exist in the array.
Chinese Description: The number of N/2 in the judging list
Solution:
def majorityelement (self, Nums): ""
: Type Nums:list[int]
: Rtype:int "" "
n = Math.floor (len ( Nums)/2
N_d = {} for
I-nums:
If I not in N_d:
n_d[i] = 1
else:
n_d[i] = N_d.get (i) + 1
for k in N_d:
if N_d.get (k) > N: Return
K
Parsing: Using a dictionary to record the number of occurrences of numbers Excel Sheet Column
English Description: Given a column title as appear in a Excel sheet, return its corresponding column number.
Example:
A-> 1
B-> 2
C-> 3
...
Z->
AA-> 27
The reverse of the problem above
Solution:
def titletonumber (self, s): ""
: Type s:str
: Rtype:int "" "
s = s[::-1]
sum1 = 0
for exp, CH AR in enumerate (s):
sum1 + = (ord (char)-1) * (+ exp) return
sum1
Resolution: Still not ... factorial trailing zeroes
English Description: Given an integer n, return the number of trailing zeroes in n!.
Note:your solution should is in logarithmic time complexity.
Returns the factorial end of N, how many 0
Solution:
def trailingzeroes (self, N): ""
: Type n:int
: Rtype:int
""
zerocnt = 0 while
n > 0:< C16/>n = N//5
zerocnt + = n return
zerocnt
Parsing: Because 0 appears to be only related to 5 Rotate Array
English Description: Rotate an array of n elements to the right by K steps.
Example:
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] are rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as and can, there are at least 3 different to ways this solve.
Chinese Description: Translate the list
Solution:
def rotate (self, nums, K): ""
: Type Nums:list[int]
: type k:int: rtype:void do not return
anything, mod Ify nums in-place instead.
"" " n = Len (nums)
k = k% n
nums[:] = nums[n-k:] + nums[:n-k]
Parsing: Adding slices with a list Reverse Bits
English Description: Reverse bits of a given bits unsigned integer.
Example:
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represent Ed in binary as 00111001011110000010100101000000).
Follow up:
The If This function is called the many, how would do you optimize it?
In Chinese: Reverses the binary representation of a number and returns the reversed integer
Solution:
def reversebits (self, n):
b = [] while
n!= 0:
b.append (n% 2)
n //= 2
If Len (b) <:
BU = [0] * (32-len (b))
b.extend (BU)
res = 0
L = Len (b) for
I in range (len (b)):
L-= 1
res + b[i] * 2 **l return
Res
Parse: Get the current number of binary, because the rules, so do not need to reverse, directly to the integer on the line, there is a place to be careful, to ensure that the length of the list is 32, not enough to fill 0 of 1 Bits
Write a function that takes a unsigned integer and returns the number of ' 1 ' bits it has also known as the Hamming Weight).
Example:
For example, the 32-bit integer ' One ' has binary representation 00000000000000000000000000001011, so the function should re Turn 3.
Returns an integer to convert to binary when there are several 1
Solution:
def hammingweight (self, N): ""
: Type n:int
: Rtype:int
"" "
B = [] while
n!= 0: