1.暴力法,时间复杂度O(n^2),空间复杂度:O(1)
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i+1; j < nums.length; j++) {
if (nums[i] + nums[j] == target){
return new int[] {i, j};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
2.一遍哈希表,时间复杂度O(n),空间复杂度:O(n)
只遍历了包含有 n 个元素的列表一次。在表中进行的每次查找只花费 O(1) 的时间。
所需的额外空间取决于哈希表中存储的元素数量,该表最多需要存储 n 个元素。
//一遍哈希表
public int[] twoSum_Hash(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
int complement;
for (int i = 0; i < nums.length; i++) {
complement = target - nums[i];
//检查HashMap中是否有满足条件的
if (map.containsKey(complement)) return new int[] {map.get(complement), i};
//没有就将当前值和下标存入HashMap中
else map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
End, thanks for reading.