1.两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
思路:
本题数组是无序的
因此可以使用暴力遍历的方法
暴力遍历就是使用两个for循环,进行数组遍历,第二个循环不包括本身数字,如果碰到满足条件直接弹出结果。本种方法的时间复杂度是O(n2),空间复杂度O(1)。
为了降低上种方法的时间复杂度,我们可以使用空间换时间的策略,利用Hash Map的O(1)遍历。
因此可以先将数字存到hashmap中,然后我们在里面找到符合差值的数字即可弹出。
import java.util.HashMap;
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> hashMap=new HashMap<>();
for(int i=0;i<nums.length;i++){
int component=target-nums[i];
if(hashMap.containsKey(component)){
return new int[]{hashMap.get(component),i};
}
hashMap.put(nums[i],i);
}
throw new IllegalArgumentException("...");
}
} LeeCode刷题日记 文章被收录于专栏
包含解法,高频leecode算法题。
查看16道真题和解析