6、旋转数组的最小数字
class Solution: def minNumberInRotateArray(self, rotateArray): l = len(rotateArray) if l == 0: return 0 for i in rotateArray: if rotateArray[0] > i: return i return rotateArray[0] s = Solution() t = [3, 4, 5, 1, 2] min = s.minNumberInRotateArray(t) print(min)
7、斐波那契数列
用递归也写了,但是好像太耗时,牛客这边系统不给过
# -*- coding:utf-8 -*- class Solution: def Fibonacci(self, n): # write code here f = [0, 1, 1] if n <= 1: return f[n] if n == 2: return f[2] else: for i in range(3, n+1): f.append(f[i - 1] + f[i - 2]) return f[n] s = Solution() print(s.Fibonacci(2)) print(s.Fibonacci(3)) print(s.Fibonacci(4)) print(s.Fibonacci(5))
8、跳台阶
因为只有两种步伐(一次跳一阶或一次跳两阶)。比如跳八个台阶时:当最后一步跳一节是一类跳法(此时前七阶的跳法有跳七个台阶的跳法);当最后一步跳两阶是另一种跳法(此时前6阶的跳法有跳6个台阶的跳法),因此得到规律,if n>2,f(n) = f(n+1)+f(n-2)
class Solution: def jumpFloor(self, number): f = [0, 1, 2] if number <= 2: return f[number] else: for i in range(3, number+1): f.append(f[i - 1] + f[i - 2]) return f[number] s = Solution() print(s.jumpFloor(1)) print(s.jumpFloor(2)) print(s.jumpFloor(3)) print(s.jumpFloor(4)) print(s.jumpFloor(5))
9、变态跳台阶
根据第八题思路,由每步可以跨1-n阶,根据最后一步,可以分为n种类型。f(n) = f(1)+f(2)+....+f(n-2)+f(n-1) ; f(n) = 2*f(n-1)
class Solution: def jumpFloorII(self, number): # write code here f = [0,1,2] for i in range(3,number+1): f.append(2*f[i-1]) return f[number] s = Solution() print(s.jumpFloorII(5))
10、矩形覆盖
# -*- coding:utf-8 -*- class Solution: def rectCover(self, number): # write code here f = [0, 1, 2] for i in range(3, number + 1): f.append(f[i - 1] + f[i - 2]) return f[number] s = Solution() print(s.rectCover(4))