『1』暴力法
class Solution {
// Brute Force
// Time Complexity: O(n^2)
// Space Complexity: 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++) {
int sum = nums[i] + nums[j];
if (sum == target) {
return new int[] {i, j};
}
}
}
return new int[0];
}
}
『2』哈希表法
class Solution {
// HashMap
// Time Complexity: O(n)
// Space Complexity: O(n)
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int diff = target - nums[i];
if (map.containsKey(diff)) {
return new int[] {i, map.get(diff)};
}
map.put(nums[i], i);
}
return new int[0];
}
}
标签:map,return,nums,int,Sum,Complexity,new,LeetCode,两数
From: https://www.cnblogs.com/torry2022/p/17919986.html