《編程之美》裏的一個題目:可否快速找出一個數組中的兩個數字,讓這兩個數字之和等於一個給定的值,假設這個數組中確定存在至少一組符合要求的解。面試
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. less
You may assume that each input would have exactly one solution. code
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2 排序
Leetcode的要求要返回索引,比編程之美的要難一些,leetcode論壇裏討論的是用hashmap來作的,實際應用中是能夠的,面試時用hashmap就不必定被面試官容許了,若是不容許怎麼辦呢?索引
一個辦法是複製原來的數組,並對其排序,排序後的數組有額外一個值保存其原來數組的索引,而後再用變成有序數組,就好作了,不過這樣須要O(n)的內存空間,但Hashmap也是O(n)的內存空間,計算效率最小爲nlgn,比用hashmap稍遜一籌。內存