Article Directory
Title Description
An incrementing input and a digital sorted array S, find the two numbers in the array, and so that they are exactly S, and if a plurality of digits equal to S, the product of the output of the minimum number of two.
Output Description:
Corresponding to each test case, the output of two numbers, the first small output.
analysis
- Method a: double loop
暴力解法
, and get all the two numbers, the time complexity is O ( )。 - Method two: full use of the
数组递增有序
features provided pointers to two数组的两头
, and the large, a large reduction in the pointer, and a small, small increases pointer equal a return pointer to meet two exit the loop. Similarly if the output of the two numbers乘积最大
, the initial两指针指向中间两个数
, to move to either side.
Code
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code here
if not array:
return []
lowP = 0
highP = len(array)-1
while lowP<highP:
if array[lowP]+array[highP]<tsum:
lowP += 1
elif array[lowP]+array[highP]>tsum:
highP -= 1
else:
return array[lowP],array[highP]
return []