LeetCode 题解 - 01.Two Sum

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 都搞的炸栈工程师。博客持续更新,如果觉得写的不错,欢迎来一波老铁三连,不好的话也欢迎指正,互相学习,共同进步。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值