博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
《剑指offer》和为S的两个数字
阅读量:4347 次
发布时间:2019-06-07

本文共 937 字,大约阅读时间需要 3 分钟。

本题来自《剑指offer》 

题目:

   输入一个递增排序的数组和一个数字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
tsum: #if cursum large target ahead -= 1 #then,previous else: behind += 1 #if cursum small target,then later return result

转载于:https://www.cnblogs.com/missidiot/p/10783745.html

你可能感兴趣的文章
文件夹及文件操作
查看>>
Python后台开发Django(会话控制)
查看>>
【BZOJ-1260】涂色paint 区间DP
查看>>
Redis学习记录之Java中的初步使用
查看>>
Eclipse Regular expression grammar
查看>>
embOS实时操作系统 - API
查看>>
小工具的使用
查看>>
146. LRU Cache && 460. LFU Cache
查看>>
POJ 1658 Eva's Problem
查看>>
jQuery Validation ,调用valid方法时,不验证remote
查看>>
构建菜单树
查看>>
数据结构
查看>>
7. Spring bean 的作用域
查看>>
jquery submit() 提交失败
查看>>
NPM错误
查看>>
微信小程序在开发中遇到的问题与解决方法
查看>>
编写了一个简单的矩阵类,可以实现矩阵的加减乘运算和求行列式等等
查看>>
测试工具网址大全(转)
查看>>
巧用bat批量开启关闭服务
查看>>
C/C++ static总结
查看>>