题目如下:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
思路:
最简单直接的想法就是,循环数据,依次判断都否有与当前值的和等于目标值的,所以需要循环两次,外循环所有数据,内循环判断和。代码如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i < nums.length; i++){
for(int j=i+1; j < nums.length; j++){
if(target == nums[j] + nums[i])
return new int[]{j,i};
}
}
return null;
}
}
image.png
分析: 时间复杂度:O(n2),因为用到双重循环。
空间复杂度:O(1)
思路二:通过上一中解法的复杂度分析,如果有更好的解法,应该是时间复杂度要低一些,这时我们立马想到hash这种数据结构,一种典型的空间换取时间的做法,这也是比较常规的做法,代码如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
int arr[] = new int[2];
HashMap<Integer,Integer> map = new HashMap();
for(int i = 0; i< nums.length; i++){
int temp = target - nums[i];
if(map.containsKey(temp)){
arr[0] = map.get(temp);
arr[1] = i;
return arr;
}
map.put(nums[i],i);
}
return null;
}
}
image.png
分析:时间复杂度O(n)
空间复杂度O(n)