1. Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

采用哈希表储存遍历过的数值及下标,查表如果有键则返回其下标及当前下标。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
int[] ans = new int[2];

for (int i = 0; i < nums.length; i++){
int result = target - nums[i];
if ( map.containsKey(result) ){
ans[0] = map.get(result);
ans[1] = i;
return ans;
}
else{
map.put(nums[i], i);
}
}
return ans;
}
}

Author

Xander

Posted on

2022-04-03

Updated on

2022-05-02

Licensed under

Comments