题目
这道题大概意思就是说给你一个数组,再给你一个目标数字,让你在数组里面找到两个和为目标数的数组下标。
中文版
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。你可以按任意顺序返回答案。
样例:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1]
注意:
2 <= nums.length <= 10^3
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9
只会存在一个有效答案
英文版
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Constraints:
2 <= nums.length <= 10^3
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9
Only one valid answer exists.
题解
1.暴力求解
时间复杂度为O(n^2),时间复杂度较高,耗时长,不提倡
package com.cute.leetcode.editor.cn;
public class TwoSum {
public static void main(String[] args) {
Solution solution = new TwoSum().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] twoSum(int[] nums, int target) {
/*
思路:暴力求解
两层循环,一个个的相加比较
*/
int flag=0;
int[] result = new int[2];
for (int i = 0; flag==0 && i < nums.length; i++) {
for (int j = i;flag==0 && j < nums.length; j++) {
//同一个元素只能使用一次
if (i!=j && nums[i] + nums[j] == target){
result[0]=i;
result[1]=j;
}
}
}
return result;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
2.优化解法,使用HashMap
用空间换时间,减少内层循环,将时间复杂度降为O(n)
采取用一个HashMap进行登记的过程,当遍历到某个位置发现该位置上的数已经存在于map中(证明前面有人需要我了),然后value就是需要的数值的下标
package com.cute.leetcode.editor.cn;
import java.util.HashMap;
public class TwoSum {
public static void main(String[] args) {
Solution solution = new TwoSum().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] twoSum(int[] nums, int target) {
//假设我们最后所需要的数组下标分别为A和B
//HashMap<Key,Value>中Key为所需要的数值,Value为其对应的数组下标
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for (int i = 0; i < nums.length; i++) {
if (!map.containsKey(nums[i])) {
//此时,循环到i=A,并向map装入另一个所需要的数值,即B对应的值
map.put(target-nums[i],i);
}else {
//HashMap中get(),获取的是指定key所对应的value值
//如果map中包含了当前循环到的值,说明我们已经遍历到我们目标B,此时i=B
//所以map.get(nums[i])的值为之前已经装入的A
return new int[]{map.get(nums[i]),i};
}
}
return null;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}