leetcode算法—两数之和 Two Sum
关注微信公众号:CodingTechWork,一起学习进步。
题目
Two Sum:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
两数之和 :
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解题
1 暴力解题
class Solution {
public int[] twoSum(int[] nums, int target) {
//遍历每个元素nums[i],查找是否存在值nums[j]相加后等于target。
for (int i = 0; i < nums.length; i++){
for(int j = i+1; j < nums.length;j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return null;
}
}
这种暴力解题,两层循环,每个元素遍历一遍,内部嵌套再把剩余的每个元素遍历一遍求和寻找目标合适元素,时间复杂度为o(n^2)
,空间复杂度为o(1)
。
2 2次遍历解题
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap();
//存储到HashMap中
for (int i = 0; i < nums.length; i++){
map.put(nums[i], i);
}
//遍历数组
for (int i = 0; i < nums.length; i++) {
//算差值
int result = target - nums[i];
//在map中查找索引不是本身i的的差值即为结果值
if(map.containsKey(result) && map.get(result) != i) {
return new int[] {i,map.get(result)};
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
这种两遍哈希表的方式,哈希表存储n个元素,增加了空间复杂度,第一次是遍历数组插入到哈希表中,时间复杂度为o(n)
,但是第二次查询时间由原来遍历数组的o(n)
减少到o(1)
。所以总体时间复杂度为o(n)
,空间复杂度为o(n)
。
3 一次遍历解题
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
//计算结果
int result = target - nums[i];
//map中是否包含这个结果,若包含则返回该结果,及对应的目前数组的index
if (map.containsKey(result)) {
//map是后添加元素的,所以map索引在前,i在后
return new int[]{map.get(result), i};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("no two sum solution");
}
}
这种方式也是参考了题解中的第一个官方的,自己想不到;他是采用了一次遍历的同时,最后将前面遍历的值放入到map中,然后后续的遍历过程中,不断的把map的值(也就是数组中已遍历的前方值)和当前后方值做比较。所以返回的时候,map的索引在前,i在后。
参考 two sum
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)