题目描述

题目链接
https://leetcode.com/problems/two-sum/
方法思路
Approach1:
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i < nums.length; i++){
for(int j = nums.length - 1; j > i; j--){
if(nums[i] + nums[j] == target){
return new int[]{i, j};
}
}
}
return new int[2];
}
Approach2:Two-pass Hash Table
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
Approach3:One-pass Hash Table
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
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 two sum solution");
}
本文详细介绍了LeetCode上经典问题“两数之和”的三种解法:暴力法、两次哈希表法及一次哈希表法。通过对比不同方法的时间复杂度与空间复杂度,帮助读者理解并掌握高效解决问题的技巧。
855

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



