快速寻找满足条件的两个数

《编程之美》里的一个题目:能否快速找出一个数组中的两个数字,让这两个数字之和等于一个给定的值,假设这个数组中肯定存在至少一组符合要求的解。

LeetCode的题目:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

Leetcode的要求要返回索引,比编程之美的要难一些,leetcode论坛里讨论的是用hashmap来做的,实际应用中是可以的,面试时用hashmap就不一定被面试官允许了,如果不允许怎么办呢?

一个办法是复制原来的数组,并对其排序,排序后的数组有额外一个值保存其原来数组的索引,然后再用变成有序数组,就好做了,不过这样需要O(n)的内存空间,但Hashmap也是O(n)的内存空间,计算效率最小为nlgn,比用hashmap稍逊一筹。

原文地址:https://www.cnblogs.com/whyandinside/p/3926966.html