持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情
Leecode每日一题:Leecode001
地址为:1. 两数之和 - 力扣(LeetCode)
题目描述:给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。注:暴力法时间复杂度过高,不推荐
示例一:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
实例二:
输入: nums = [3,3], target = 6
输出: [0,1]
方法一:暴力算法
方法描述:采用两层for循环,内层从0开始到nums.length,外层从1开始到nums.length,然后依次遍历数组中每个元素,如果找到两个数等于target目标数,就返回这两个数的数组索引。
Java代码:
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(nums[j] + nums[i] == target) {
return new int[] {i, j};
}
}
}
return new int[] {};
}
时间复杂度:时间复杂度为O(N^2)。
空间复杂度:不考虑原数组的情况下,空间复杂度为O(1)。
方法二:哈希表法
方法描述:采用Hash表,Hash表的key为数组元素的值,value为数组元素的索引下标,先将数组全部存到map集合中,然后利用for循环判断哈希表中是否存在target-nums[i],如果Hash表中存在,返回i和map集合对应(target-nums[i])元素的value并存到结果集数组中。
Java代码:
public static int []twoSum10(int[] nums, int target){
int[] arr=new int[2];
//将 nums数组中的元素全部存到target
HashMap<Integer,Integer> map=new HashMap<>();
for (int i = 0; i <nums.length ; i++) {
map.put(nums[i],i);
}
//寻找 target-nums[j]; 如果找到 就存到arr数组中 并返回
for (int j = 0; j < nums.length; j++) {
int chazhi=target-nums[j];
if (map.containsKey(chazhi)&&map.get(chazhi)!=j){
arr[0]=j;
arr[1]=map.get(chazhi);
return arr;
}
}
return arr;
}
时间复杂度:O(N),其中 N 是数组中的元素数量。对于每一个元素 x,我们可以 O(1) 地寻找 target - x。 空间复杂度:O(N),其中 N 是数组中的元素数量。主要为哈希表的开销。