class Solution {
public int[] twoSum(int[] nums, int target) {
// 用 map 集合存储遍历过的元素,相比较两层循环遍历
// 时间复杂度由 O(N²)减少至 O(N)
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
return new int[]{i, map.get(target - nums[i])};
}
map.put(nums[i], i);
}
return new int[0];
}
}
leetcode-1-两数之和
最新推荐文章于 2024-06-15 20:34:11 发布