-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwoSum
More file actions
19 lines (18 loc) · 944 Bytes
/
twoSum
File metadata and controls
19 lines (18 loc) · 944 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class twoSum(){
public int[] twoSum(int[] nums, int target){
int len = nums.length;
Map<Integer, Integer> map = new HashMap<>(len - 1);
HashMap.put(nums[0], 0);
for (int i = 1; i < len; i++){
if (HashMap.containsKey(target - nums[i])){
return new int[]{HashMap.get(target - nums[i]), i};
}
HashMap.put(nums[i], i);
}
}
}
//题目:给定一个整数数组nums和一个整数目标值target,请你在该数组中找出和为目标值的那两个整数,并返回它们的数组下标
//思路:哈希表存储数组元素,遍历数组,判断哈希表中是否存在target-nums[i],存在则返回下标,不存在则将nums[i]存入哈希表
//https://leetcode.cn/problems/two-sum/solutions/434597/liang-shu-zhi-he-by-leetcode-solution/
//时间复杂度O(n) n为数组长度
//空间复杂度O(n) 哈希表最多存n-1个数