1.两数之和Java
题目描述
给定整数数组 nums 和整数目标值 target,请你在该数组中找出 和为目标值的那两个整数,并返回它们的数组下标。
每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
输入输出样式
示例1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
本文题来自LeetCode:https://leetcode-cn.com/problems/two-sum/
思路
- 二重循环遍历数组,找到相加为target的两个数x, y,返回二者的下标。
- 使用哈希表查找,能把找target - x的时间复杂度从O(N)降低到O(1);先创建一个哈希表,对于每一个 x,我们首先查询哈希表中是否存在 target - x,然后将 x 插入到哈希表中,保证 x 不会和自己匹配
算法分析
- 时间复杂度为O(N²),空间复杂度为O(1)
- 时间复杂度为O(N),空间复杂度为O(N)
求解函数
//解法一
public int[] twoSum(int[] nums, int target) {
int[] index = new int[]{-1, -1};
for (int i = 0; i < nums.length; ++i)
for (int j = i + 1; j < nums.length; ++j){
if (nums[i] + nums[j] == target){
index[0] = i;
index[1] = j;
return index;
}
}
return index;
}
//解法二:哈希表
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; ++i) {
if (hashtable.containsKey(target - nums[i])) {
return new int[]{hashtable.get(target - nums[i]), i};
}
hashtable.put(nums[i], i);
}
return new int[0];
}
}
主函数调用
class Solution1 {
public static void main(String[] args) {
int[] nums = new int[]{2, 7, 11, 15};
Solution1 sol = new Solution1();
int[] rst = sol.twoSum(nums, 9);
System.out.print(rst[0] + ", " + rst[1]);
}
public int[] twoSum(int[] nums, int target) {...}
}