Problem:

Given an array of integers that is already sorted in ascending order, 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

Solutions:

1-Two-Sum 的改动版,有序的数组就可以考虑使用二分搜索进行查找,偷懒写了递归版,本以为使用 slice 写二分查找会比较赞,但是实际上并没有简化的感觉。

Problem:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

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

Example:

The returned answers should be zero-based.

Solutions:

Brute Force 不值一提,本该用 HashTable 解决的问题在遇到了 Go 自带的 map 后就变得十分简单了,虽然写一个开地址哈希表也并不费事。