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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
我的做法:
相当于brute force啦,用两个for循环搞定。
缺点:
当然是很慢啦
改进:
用字典做,只需要一个循环,在循环的过程中,让结果等于target减去num[i],如果target-num[i]在字典里的话,就输出这个target-num[i]对应的下标,否则就将num[i]作为key,i作为value。