LeetCode-1:Two Sum (固定和的元素的索引)

本文介绍了一种高效解决两数之和问题的算法。通过使用哈希表,该算法能在单次遍历中找到数组中两个数相加等于特定目标值的元素,并返回它们的索引。这种方法避免了双重循环的复杂度,显著提高了查找速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Question

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].

问题解析:

从给定数组中,找到两个和为目标数值的两个元素,返回元素在数组中的索引值。

Answer

Solution 1:

排除循环嵌套的暴力搜索法,能想到的一种解法就是利用Map去实现。

  • 观察题目可知,如题例子:9-2=7,所以我们可以通过判断target - nums[i] 的结果是否已经存在于Map中,就可以一次遍历找到两个对应的目标值;
  • 如果结果不存在Map中,则保存相应的nums[i],一旦找到则返回结果;
  • 其中,Map中保存的值对是目标元素和其对应的索引。
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i=0; i<nums.length; i++){
            if (map.containsKey(target - nums[i])){
                result[0] = map.get(target - nums[i]);
                result[1] = i;
                return result;
            }
            map.put(nums[i], i);
        }
        return result;
    }
}
  • Runtime:7 ms
  • Beats 91.39 % of java submissions
  • 时间复杂度:O(n),空间复杂度:O(n)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值