Sharing of answers to questions 6-10 of sword finger offer -- python implementation

Posted by noiseusse on Fri, 20 Dec 2019 15:34:24 +0100

'''''
'''
6. Title Description
To move the first elements of an array to the end of the array, we call it the rotation of the array.
Input a rotation of a non subtractive sort array, and output the minimum elements of the rotation array.
For example, array {3,4,5,1,2} is a rotation of {1,2,3,4,5} and the minimum value of the array is 1.
NOTE: all the given elements are greater than 0. If the array size is 0, please return 0.
'''

class Solution:
    def minNumberInRotateArray(self, rotateArray):
        if rotateArray is None:
            return 0
        else:
            list = []
            n = len(rotateArray)
            for i in range(n):
                list.append(rotateArray[n-1-i])
                i +=1
            min = 0
            j = 1
            while j < n:
                if list[min]<=list[j]:
                    j +=1
                else:
                    min = j
                    j +=1
            return list[min]

'''
7. Title Description
Everyone knows the Fibonacci sequence. Now you need to input an integer n. please output the nth term of the Fibonacci sequence (starting from 0, 0).
n<=39
'''

class Solution:
    def Fibonacci(self, n):
        # write code here
        result = [0,1,1,2]
        while len(result)<=n:
             result.append(result[-1]+result[-2])
        return result[n]

'''
8. Title Description
A frog can jump up one or two steps at a time. Find out how many kinds of jumping methods are there for the frog to jump to an n-level step (different results are calculated according to different order).
'''

class Solution:
    def jumpFloor(self, number):
        if number==0|number==1|number==2:
            return number
        else:
            result = [0,1,2]
            while len(result)<=number:
                result.append(result[-1]+result[-2])
            return result[number]

'''
9. Title Description
A frog can jump up one step or two at a time It can also jump to level n. Find out how many ways the frog can jump to an n-level step.
'''

class Solution:
    def jumpFloorII(self, number):
        # write code here
        if number==0|number==1|number==2:
            return number
        else:
            result = [0,1,2]
            while len(result)<=number:
                result.append(result[-1]*2)
            return result[number]

'''
10. Title Description
We can use the small rectangle of 21 to cover the larger rectangle horizontally or vertically. How many ways can I cover a 2*n large rectangle with n 21 small rectangles without overlapping?
'''

class Solution:
    def rectCover(self, number):
        result = [0,1,2]
        while len(result)<=number:
            result.append(result[-1]+result[-2])
        return result[number]