/*
* Given an array of integers, return indices of the two numbers such that they add up
* to a specific target.
* You may assume that each input would have exacly one solution, and you may not use
* the same element twice.
* Example:
* Give nums = [2, 7, 11, 15], target = 9,
* Because nums[0] + nums[1] = 2 + 7 = 9,
* return [0,1]
*/
- 暴力
暴力算法时间复杂度O(n²),空间复杂度O(1)
public class TwoSum {
public static void main(String[] args) {
int[] nums = new int[] {2, 7, 11, 15};
int target = 9;
int[] result = twoSum(nums, target);
for(int i : result) {
System.out.print(i + "\t");
}
}
public static int[] twoSum(int[] nums, int target) {
ArrayList<Integer> resultList = new ArrayList<Integer>();
for(int i = 0; i < nums.length; i++) {
for(int j = i + 1; j < nums.length; j++) {
if(nums[i] + nums[j] == target) {
resultList.add(i);
resultList.add(j);
}
}
}
int[] result = new int[resultList.size()];
for(int i = 0; i < resultList.size(); i++) {
result[i] = resultList.get(i);
}
return result;
}
}
- 两次遍历 HashMap
时间复杂度:O(n),
我们把包含有 n 个元素的列表遍历两次。由于哈希表将查找时间缩短到 O(1) ,所以时间复杂度为 O(n)。
空间复杂度:O(n),
所需的额外空间取决于哈希表中存储的元素数量,该表中存储了 n 个元素。
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
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.");
}
- 一次遍历 HashMap
进行迭代并将元素插入到表中的同时,回过头来检查表中是否已经存在当前元素所对应的目标元素。如果它存在,那找到了对应解,并立即将其返回
时间复杂度:O(n),
我们只遍历了包含有 n 个元素的列表一次。在表中进行的每次查找只花费 O(1) 的时间。
空间复杂度:O(n),
所需的额外空间取决于哈希表中存储的元素数量,该表最多需要存储 n 个元素。
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
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.");
}
网友评论