The solution to Problem on slide 5:
basically use recursion to get the power of the square root of the number you need, make sure to factor in the remainder.
class Solution(object):
def myPow(self, x, n):
if n<0:
return 1/myPow(x,n)
if n==0:
return 1
if n==1:
return x
val = self.myPow(x,n//2)
return val*val * self.myPow(x,n%2)
The solution to Problem on slide 6:
This is a memory-efficient approach where you get the length of the list and iterate twice to get the answer.
class Solution(object):
def removeNthFromEnd(self, head, n):
count= 0
begin = head
while head!=None:
head = head.next
count+=1
if count ==1 and n==1:
return None
head = begin
for i in range(count-n-1):
head = head.next
if count-n ==0:
return head.next
if n >1:
head.next = head.next.next
else:
head.next=None
return begin
The solution to Problem on slide 7:
derive the general rotate function, get 4 rotated points for each point in the first quadrant, then rotate all of them in place.
class Solution(object):
def rotate(self, matrix):
n = len(matrix)
odd = (n%2)
def rotate(i,j):
return j, n-i-1
for i in range(n//2 + odd):
for j in range(n//2):
i1,j1 = rotate(i,j)
i2,j2 = rotate(i1,j1)
i3,j3 = rotate(i2,j2)
matrix[i][j],matrix[i1][j1],matrix[i2][j2],matrix[i3][j3]\
=matrix[i3][j3],matrix[i][j],matrix[i1][j1],matrix[i2][j2]
return matrix
Feel free to ask me if you have any questions.