Leetcode 第 01. Two Sum 题,题目难度 Easy。
一. 题目要求
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
二. 解题思路 & 代码实现
这道题有三种解法
1. 暴力破解
我们可以查看所有数组元素的两两组合,找到满足条件的组合的索引,虽然可行但速度很慢,这里不做讨论。
2. 数组遍历
从第 0 个元素开始,依次与其后面的元素相加看是否满足条件,如果满足则返回对应的索引。最坏情况下需要从 0 遍历到 n-1,时间复杂度为 𝑛(𝑛−1)2,性能依然很低。
3. HashMap 方式
这里最终的解决方案是采用 空间换时间的方式,引入一个 HashMap 记录数组中的索引和值(index,value),如果后续遍历时 Map 包含的值 满足:target - value ,则满足条件,返回对应的索引即可,代码如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
int length = nums.length;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i< length; i ++) {
int num = nums[i];
if (map.containsKey(target - num)) {
return new int[]{map.get(target - num), i};
}
map.put(num, i);
}
return new int[]{0, 0};
}
}
- 运行结果
Runtime: 1 ms, faster than 99.97% of Java online submissions for Two Sum.
老铁都看到这了来一波点赞、评论、关注三连可好
我是 AhriJ邹同学,前后端、小程序、DevOps 都搞的炸栈工程师。博客持续更新,如果觉得写的不错,欢迎来一波老铁三连,不好的话也欢迎指正,互相学习,共同进步。