classSolution: defFindkthToTail(self,head,k): ifnot head or k == 0: returnNone tmpNode = head for i inrange(0,k): if tmpNode: tmpNode = tmpNode.next else: returnNone kNode = head while tmpNode: kNode = kNode.next tmpNode = tmpNode.next return kNode
classSolution: defquicksort(self,lists,left,right): x = lists[right] i = left - 1 for j inrange(len(lists)-1): if lists[j] < x: i += 1 lists[i],list[j] = lists[j],lists[i] lists[i+1],lists[right] = lists[right],lists[i+1] return i+1 defquicksortself(self,lists,left,right): if left < right: num = self.quicksort(lists,left,right) quicksort(lists,left,num-1) quicksort(lists,num+1,right)
classSolution: deffind1count(self,num): if num == 0: return0 count = 1 if num == -1: return32 if num == -2147483648: return1 if num < 0: num = num & 0x7FFFFFFF count +=1 num = num & (num - 1) while num!=0: count += 1 num = num & (num - 1) return count
看到的最简洁的代码是这个
1 2 3
classSolution: defone(self,num): returnsum([(num >> i & 1) for i inrange(0, 32)])
输入一个数组,实现一个函数,让所有奇数都在偶数前
python可以用sorted方法,参数key使用判断奇偶数的lambda表达式即可。
正经方法的话,借用快速排序的思路,完成一次快排即可
1 2 3 4 5 6 7 8 9 10
classSolution: defRecordOddEven(self,lists): i = -1 j = 0 while j <= len(lists): if lists[j] % 2 != 0: i += 1 lists[i],list[j] = lists[j],lists[i] j +=1 return lists
判断一个字符串是否是另一个字符串的子串
python可以用in操作符,string模块的find方法,index方法,这些就不赘述了。
1 2 3 4 5 6 7 8 9
classSolution: defcheckchild(self,s1,s2): j = 0 for i inrange(len(s2)): while j < len(s1) and s1[i] != s2[j]: j+=1 if j == len(s1): returnFalse returnTrue
暴力按序统计
把一个int型数组中的数字拼成一个串,这个串代表的数字最小
把数组里所有数转为字符串,再把字符串拼在一起,排序,如果首位是0,就和之后第一个不是0的数交换
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defgetmin(self,lists): l='' for i in lists: l+=str(i) l = list(l) l.sort() if l[0] == '0': for i inrange(1,len(l)): if l[i] != '0': l[0],l[i]=l[i],l[0] break s=''.join(l) returnint(s)