import sys arrList = sys.stdin.readline().strip('\n') arrList = list(map(int, arrList.split())) M = int(sys.stdin.readline().strip()) print(arrList, M) res=0 arrList_len = len(arrList) for i in range(arrList_len): for j in range(i+1, arrList_len): if (arrList[i] + arrList[j]) <= M: print(i,j) res+=1 print(res)
2字符串的第k个字符
这个题很明显的递归,自己想麻烦了,我的思路是按照递归先生成字符串,但是这样就会出现很大的问题,超时很严重
class Solution: def findKthBit(self, n, k): len_n = 2 ** n - 1 mid = int(len_n / 2)+1 if k == mid: return chr(ord('a') + n - 1) elif k<mid: return self.findKthBit(n-1,k) else: c= self.findKthBit(n-1,len_n-k+1) return chr(ord('z')-ord(c)+ord('a')) S=Solution() print(S.findKthBit(26,23))3.小朋友分纸张,其实就是分发糖果的变形题
class Solution: def candy(self, ratings): left = [1 for _ in range(len(ratings))] right = left[:] for i in range(1, len(ratings)): if ratings[i] > ratings[i - 1]: left[i] = left[i - 1] + 1 count = left[-1] for i in range(len(ratings) - 2, -1, -1): print(i) if ratings[i] > ratings[i + 1]: right[i] = right[i + 1] + 1 count += max(left[i], right[i]) print(left,right) return count s=Solution() print(s.candy([1,2,3,2,4,1]))4.二维数组最短路径,注意题目条件第一个点不计算代价
class Solution: def minSailCost(self, input): m, n = len(input), len(input[0]) inf = float('inf') dp = [[0] * n for _ in range(m)] dp[0][0] = input[0][0] for j in range(1, n): if input[0][j] == 1: dp[0][j] = dp[0][j - 1] + 1 elif input[0][j] == 0: dp[0][j] = dp[0][j - 1] + 2 else: dp[0][j] = dp[0][j - 1] + inf for i in range(1, m): if input[i][0] == 1: dp[i][0] = dp[i - 1][0] + 1 elif input[i][0] == 0: dp[i][0] = dp[i - 1][0] + 2 else: dp[i][0] = dp[i - 1][0] + inf for i in range(1, m): for j in range(1, n): temp = min(dp[i - 1][j], dp[i][j - 1]) if input[i][j] == 1: dp[i][j] = temp + 1 elif input[i][j] == 0: dp[i][j] = temp + 2 else: dp[i][j] = temp + inf if dp[m - 1][n - 1] >= inf: return -1 else: return dp[m - 1][n - 1]-dp[0][0] S = Solution() print(S.minSailCost([[1, 1, 1, 1, 0], [0, 1, 0, 1, 0], [1, 1, 2, 1, 1], [0, 2, 0, 0, 1]]))z
总结:不怕丑,四道题我没有一道题全对,第一道题,题目条件看错了,第二道题递归思路出错,第三道题没做出来,第四道题自己明明做过在初始化边界条件时出错,
自己应该是凉了,但是也不能回避问题,每次笔试面试做好复盘,加油!!!
全部评论
(0) 回帖