题目描述

解决思路
使用HahMap,利用其时间复杂度为O(1)的特点,并且将当前数值作为Key进行保存
代码
class Solution {
public int[] twoSum(int[] nums, int target) {
//使用HashMap解决问题
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i++){
int complement = target - nums[i];
if(map.containsKey(complement)){
return new int[]{map.get(complement),i};
}
map.put(nums[i],i);
}
throw new IllegalArgumentException("No solutions");
}
}
复杂度分析
时间复杂度:O(n),因为把数组遍历了一遍
空间复杂度:O(n),新建的HashMap把数组全部存储了一遍
 leetcode1.两数之和 - 20250326&spm=1001.2101.3001.5002&articleId=146558623&d=1&t=3&u=d45b9fcfbcbb4f039299e3126aa94f63)
224

被折叠的 条评论
为什么被折叠?



