14、和为S的两个数:
题目描述
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
输出描述:
对应每个测试案例,输出两个数,小的先输出。
笔记:自己写加调试出来了,但是复杂了好多,看排行,好简洁
方法1:
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code here
# 因为是递增数组,所以最靠两边的一对就是积最小的
l = []
for x in array:
l.append(tsum-x)
for y in l:
if y in array:
return [tsum-y,y]
return []
方法2:自己的,太不简洁了
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code here
ans = []
i = 0
j = len(array)-1
while i < len(array)-1 and j > 0:
res = []
if array[i] + array[j] == tsum:
res.append(array[i])
res.append(array[j])
ans.append(res)
i += 1
j -= 1
if array[i] + array[j] > tsum:
j -= 1
if array[i] + array[j] < tsum:
i += 1
if len(ans) == 0:
return []
else:
return ans[0]
15、求1+2+3+…+n的和
题目描述
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
# -*- coding:utf-8 -*-
class Solution:
def Sum_Solution(self, n):
# write code here
return n and (n + self.Sum_Solution(n-1))
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.sum = 0
def Sum_Solution(self, n):
# write code here
def qiusum(n):
self.sum += n
n -= 1
return n>0 and self.Sum_Solution(n)
qiusum(n)
return self.sum