1 Two Sum

博客围绕给定整数数组,找出两数之和等于特定目标值的索引问题展开。介绍了一种解法思路,通过游标遍历数组,利用哈希表查找符合条件的数。该解法时间复杂度和空间复杂度均为O(N)。

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

题目

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


解法思路(一)

  • 游标 i[0, nums.length) 间遍历,每遍历到一个数,就在其前遍历过的数中找 target - nums[i],这个找的动作是依赖于哈希表完成的(HashMap),如果找到了,就得到解了,如果没找到,就把当前数放入哈希表,键为 nums[i],值为 i

解法实现(一)

时间复杂度
  • O(N);
空间复杂度
  • O(N);
关键词

哈希表 HashMap

package leetcode._1;

import java.util.HashMap;

public class Solution1_1 {

    public int[] twoSum(int[] nums, int target) {

        HashMap<Integer, Integer> toFindComplement = new HashMap<>(nums.length);

        for(int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            Integer indices = toFindComplement.get(complement);
            if (indices != null) {
                return new int[]{indices.intValue(), i};
            }
            toFindComplement.put(nums[i], i);
        }

        throw new RuntimeException("No result!");
    }

    public static void main(String[] args) {
        int[] arr = {2, 7, 11, 15};
        int[] result = (new Solution1_1()).twoSum(arr, 9);
        for (int i = 0; i < result.length; i++) {
            if (i == result.length - 1) {
                System.out.println(result[i]);
            } else {
                System.out.print(result[i] + " ");
            }
        }

        System.out.println(result.length);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值