「这是我参与11月更文挑战的第1天,活动详情查看:2021最后一次更文挑战」。
今天我们一起来看看LeetCode上神奇的两数之和如何求解
题目描述
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 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]
题目解法
Java实现方法之一哈希表,使用哈希表用来维护数组的值和指针,方便同目标值比较,即刻返回所需指针位置。
时间复杂度和空间复杂度均为O(n)。
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashMap = new HashMap();
for(int i = 0; i < nums.length; i ++){
int curNum = nums[i];
int calNum = target - curNum;
Integer lastIndex = hashMap.get(calNum);
if(lastIndex != null){
return new int[]{lastIndex, i};
}else{
hashMap.put(curNum, i);
}
}
return new int[2];
}
}
Java实现方法之二暴力求解,所谓暴力求解,即双层循环便利所有可能加和值,即刻返回当前内外循环的指针。
不难看出,时间复杂度为O(n平方),因未引入其他变量,空间复杂度为O(1)
class Solution {
public int[] twoSum(int[] nums, int target) {
int length = nums.length;
for (int i = 0; i < length; ++i) {
for (int j = i + 1; j < length; ++j) {
if (nums[i] + nums[j] != target) {
continue;
}
return new int[]{i, j};
}
}
return new int[2];
}
}
LeetCode原题链接:leetcode-cn.com/problems/tw…