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 后就变得十分简单了,虽然写一个开地址哈希表也并不费事。

 

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.

Example:
For num = 5 you should return [0,1,1,2,1,2].

Follow up:

  • It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
  • Space complexity should be O(n).
  • Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

Hint:

  1. You should make use of what you have produced already.
  2. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
  3. Or does the odd/even status of the number help you in calculating the number of 1s?

一开始没看 Hint ,看到题目的要求下意识的想到了树状数组中 lowbit 的用法,但是感觉这样还是不能满足 O(N) 的时间要求……

思路大体是这样的,首先从 num 开始计算出 1 的个数,然后通过形似 num-=(num&-num) 的运算消去最后一个 1 ,完成对下一个 num 的计数,然后依次类推。之后从 num 递减,若出现了未记录的数,则继续如上的计算。

代码如下: