遍历 考虑时间复杂度,空间复杂度,尽量节省.
双重for循环暴力破解
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[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
时间复杂度为O(n2)一层遍历为n,两层嵌套为n2
空间复杂度为O(1)。 看需要的额外内存
两遍哈希
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");
}
时间复杂度:O(n), 我们把包含有 n 个元素的列表遍历两次。由于哈希表将查找时间缩短到 O(1) ,所以时间复杂度为 O(n)。
实质时2*n
空间复杂度:O(n), 所需的额外空间取决于哈希表中存储的元素数量,该表中存储了 n个元素。
一遍哈希
public int[] twoSum1(int[] nums, int target) { Map<Integer, Integer> map = Maps.newHashMap(); for (int a = 0; a < nums.length; a++) { map.put(nums[a], a); int result = target - nums[a]; if (map.containsKey(result)){ return new int[] { map.get(result), a }; } } throw new IllegalArgumentException("No two sum solution"); }
-
时间复杂度:O(n), 我们只遍历了包含有 n个元素的列表一次。在表中进行的每次查找只花费 O(1) 的时间。
-
空间复杂度:O(n), 所需的额外空间取决于哈希表中存储的元素数量,该表最多需要存储 n 个元素。