Leetcode 0623
LeetCode 59 螺旋打印矩阵
class Solution: def generateMatrix(self, n: int) -> List[List[int]]: i = 0 j= 0 k = 0 t =1 d1 = 0 d2= 1 tb = [i for i in range(n)] #print(tb) a = [[0 for i in range(n)] for j in range(n)] def getdir(d1,d2): if [d1,d2]==[1,0]: return 0,-1 elif [d1,d2] ==[0,1]: return 1,0 elif [d1,d2] ==[-1,0]: return 0,1 else: return -1,0 while k<n**2: a[i][j] = t t+=1 if d1+i not in tb or d2+j not in tb or a[i+d1][j+d2]!=0: d1,d2= getdir(d1,d2) k+=1 #print(a) i = i+d1 j+=d2 # print(d1,d2,i,j) return a
leecode 56合并区间
特殊情况 输入长度为0的list
class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: new=[] intervals.sort() if len(intervals)==0: return new c =intervals[0] for i in range(1,len(intervals)): if intervals[i][0]>=c[0] and intervals[i][0]<=c[1]: c[1] = max(c[1],intervals[i][1]) else: new.append(c) c = intervals[i] new.append(c) return new
Leetcode加油站:
class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: remain = [gas[i]-cost[i] for i in range(len(gas))] for i in range(len(remain)): if remain[i]<0: continue sum1 =0 t= i k=0 while k<len(remain): sum1 = sum1+remain[t] t = t+1 if t>=len(remain): t=0 k+=1 if sum1<0: break if sum1>=0 and k==len(remain): return i return -1