zoukankan      html  css  js  c++  java
  • 《剑指offer》和为S的两个数字

    本题来自《剑指offer》 和为S的两个数字

    题目:

       输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。

    思路:

       头尾双向夹逼遍历,题目是递增排序的数组,当和大于当前值是,那么就向前遍历,如果小于那么就向后遍历。

      要求是乘积最小,理论讲,两数相距最远,其乘积最小。

    Python Code:

    # -*- coding:utf-8 -*-
    class Solution:
        def FindNumbersWithSum(self, array, tsum):
            # write code here
            result = []                                #result cache,empty
            if not isinstance(array, list):            #boundart condition judgement
                return result
            behind = 0                                 #first index of array
            ahead = len(array)-1                       #last index of array
            while behind<ahead:                        #the condition is behind small ahead
                cursum = array[behind]+array[ahead]    #summation
                if cursum==tsum:                       #if cursum equal target
                    result.append(array[behind])       #then,append the value
                    result.append(array[ahead])
                    break
                elif cursum>tsum:                      #if cursum large target
                    ahead -= 1                         #then,previous
                else:
                    behind += 1                        #if cursum small target,then later
            return result
  • 相关阅读:
    返回一个整数数组中子数组的最大值
    软工概论第二周个人项目四则运算二(改进)
    构建之法阅读笔记01
    单例模式
    .net基础加强
    使用jquery easy ui
    抽象工厂类
    System.Linq.Expressions.Expression
    创建上下文对象
    DBSesson
  • 原文地址:https://www.cnblogs.com/missidiot/p/10783745.html
Copyright © 2011-2022 走看看