avatar

目录
Algorithm: Two Sum

Description

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:

Code
1
2
3
4
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution

Use hashmap to speed up the searching. Image you have two queus:

  1. arry list stores all memebers, which is nums –> A = [2, 4, 6, 8, 10, 12, 14, 16]
  2. a hashmap, that stores member as key, position in array list as value. B = HashMap<Integer, Interger>

Now, let’s loop arry A, we will able to calculate anotherNum (target - value of member) for each member of A. if we could find anotherNum in HashMap B, then we have the answer, otherwise store member as well as its’ position into HashMap.

image-20200325105340541

Code

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] result = null;
int anotherNum = -1;
for(int i = 0;i < nums.length; i++){
anotherNum = target - nums[i];
if(map.containsKey(anotherNum)){
result = new int[]{i, map.get(anotherNum)};
return result;
}else{
map.put(nums[i],i);
}
}
return result;
}
}
文章作者: Aries Kou
文章链接: http://yoursite.com/posts/Algorithm/1512552365.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Aries' Blog
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论