每日一道面试题-两数之和
leetcode()简单:1.两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
刚开始想到的是暴力求解,时间复杂度O(n^2)
后面用一遍哈希表解,时间复杂度为O(n)
这里哈希表为什么为O(n)呢?可能会有疑问,有人会说Map源码中的containsKey()方法内部有循环。源码如下:
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
要知道,只有hashCode和地址冲突的时候,containsKey()方法才会进入这层循环,且冲突一般很少,所以这层循环可以忽略,所以认为时间复杂度为O(n)。
题目具体代码如下:
import java.util.HashMap;
import java.util.Map;
/*
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
*/
public class 两数之和 {
//暴力法
public static 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");
}
/*
一遍哈希表
*/
public static int[] twoSum3(int[] nums, int target) {
HashMap<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[]{
i, map.get(complement)};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
/*
两遍哈希表
*/
public static int[] twoSum2(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");
}
public static void main(String[] args) {
int[] ints = twoSum(new int[]{
2, 7, 11, 15}, 9);
// int[] ints = twoSum(new int[]{2, 7, 11, 15}, 9);
// int[] ints = twoSum2(new int[]{2, 7, 11, 15}, 9);
System.out.println(ints);
}
}