输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, array, tsum):
# 两头开始找匹配,乘积最小必定为最先找到的,如7+8=15 1+14=15乘积1*14小
low, high = 0, len(array) - 1
while low < high:
if array[low] + array[high] > tsum:
high -= 1
elif array[low] + array[high] < tsum:
low += 1
else:
return [array[low], array[high]]
return [] # 匹配失败返回空list
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
class Solution:
def LeftRotateString(self, s, n):
# write code here
res, length = list(s), len(s)
if n > length : return ""
for i in range(int(n/2)):
res[i], res[n-1-i] = res[n-1-i], res[i]
for i in range(n, int((n+length)/2)):
res[i], res[length-1-i+n] = res[length-1-i+n], res[i]
for i in range(int(length/2)):
res[i], res[length-1-i] = res[length-1-i], res[i]
return "".join(res)
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
class Solution:
def Sum_Solution(self, n):
# write code here
ans=n
temp=ans and self.Sum_Solution(n-1)
ans=ans+temp
return ans
4万+

被折叠的 条评论
为什么被折叠?



