LeetCode 1: Two Sum

本文深入探讨了经典的“两数之和”问题,提供了三种不同的解决方案,包括暴力穷举、使用哈希表的空间换时间策略,以及最优化的一次遍历哈希表方法。通过这些算法的对比,读者可以理解不同技术的优劣,以及如何在实际编程中选择最合适的解决方案。

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

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution1:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] index = new int[2];
        int firstIndex = 0;
        int secondIndex = 1;
        loop:for(firstIndex = 0;firstIndex < nums.length-1;++firstIndex){
            for(secondIndex = firstIndex+1;secondIndex < nums.length;++secondIndex){
                if(target == nums[firstIndex]+nums[secondIndex]){
                    break loop;
                }
            }
        }
        index[0] = firstIndex;
        index[1] = secondIndex;
        return index;
    }
}

非常暴力地穷举,具有 O(n2) O ( n 2 ) 的时间复杂度。

Solution2: 空间换时间

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        map.put(nums[i], i);
    }
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement) && map.get(complement) != i) {
            return new int[] { i, map.get(complement) };
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

Solution3: 太机智了,只扫描一次就够了

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}

加油啊少年,不要只会穷举啊!

附上题目地址:
https://leetcode.com/problems/two-sum/description/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

颹蕭蕭

白嫖?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值