思路
已知输入数组为排序数组, 使用两个指针从头和尾对数组进行遍历,
若2数之和大于目标值, 则移动右指针,减小当前数的和;
若2数之和小于目标值, 则移动左指针,增加当前数的和;
直到找到目标数据,或者2个指针相遇,结束遍历。
代码:
In [1]: def two_index_of_target_sum(array, tar):
...: left, right = 0, len(array)-1
...:
...: while left < right:
...: cur_sum = array[left] + array[right]
...: print(f'current sum: {array[left]} + {array[right]} == {cur_sum}')
...: if cur_sum == tar:
...: return left, right
...: elif cur_sum < tar:
...: left += 1
...: else:
...: right -= 1
In [2]: two_index_of_target_sum([1, 2, 3, 4, 6], 6)
current sum: 1 + 6 == 7
current sum: 1 + 4 == 5
current sum: 2 + 4 == 6
Out[2]: (1, 3)