版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014568072/article/details/87906287
41. 和为s的两个数
题目描述
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
输出描述
对应每个测试案例,输出两个数,小的先输出。
思路
《剑指offer》P214
设置两个指针,p1
从前向后,p2
从后向前移动
- 若
p1+p2>7
,则将p2
向前移动一位 - 若
p1+p2<7
,则将p1
向后移动一位
举例: 数组[1,3, 4,5, 7]
,和为7
p1 | p2 | sum | 比较 |
---|---|---|---|
1 | 7 | 8 | >7 |
1 | 5 | 6 | <7 |
3 | 5 | 8 | >7 |
3 | 4 | 7 | =7 |
code
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code here
# 设置两个指针
if not array:
return []
p1 = 0
p2 = len(array) - 1
sumtmp = array[p1] + array[p2]
while array[p1] < array[p2]:
if sumtmp < tsum:
p1 += 1
sumtmp = array[p1] + array[p2]
elif sumtmp > tsum:
p2 -= 1
sumtmp = array[p1] + array[p2]
else:
return array[p1], array[p2]
if p1 >= p2:
return []
42. 和为s的连续正数序列
题目描述
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
输出描述
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
思路
《剑指offer》P216
设置两个指针,p1
在前p2
在后,都从后向前移动
- 若
p1+p2>7
,则将p1
向前移动一位 - 若
p1+p2<7
,则将p2
向前移动一位 - 若
p1
超过p2
或者p2==sum
则停止
举例: 和为7
p1 | p2 | sum | 比较 |
---|---|---|---|
1 | 2 | 3 | <7 |
1 | 3 | 6 | <7 |
1 | 4 | 10 | >7 |
2 | 4 | 8 | >7 |
3 | 4 | 7 | =7 |
4 | 4 | 4 | <7 |
4 | 5 | 9 | >7 |
5 | 5 | 10 | >7 |
6 | 5 | p1>p2 |
stop |
结果为[3,4]
code
# -*- coding:utf-8 -*-
import copy
class Solution:
def FindContinuousSequence(self, tsum):
# write code here
if tsum <= 2:
return []
res = []
stmp = 3
p1 = 1
p2 = 2
restmp = [1,2]
while p2 < tsum and p1 <= p2:
# 如果当前和比tsum小,则继续加大值
if stmp < tsum:
p2 += 1
stmp += p2
restmp.append(p2)
# 如果当前和比tsum大,则减去小值
elif stmp > tsum:
stmp -= p1
p1 += 1
restmp.pop(0)
else:
t = copy.copy(restmp)
res.append(t)
stmp -= p1
p1 += 1
restmp.pop(0)
return res