leetcode Two Sum(Java)

本文介绍了LeetCode经典题目“两数之和”的两种解法:暴力解法和使用HashMap的解决方案。暴力解法通过双重循环遍历数组,时间复杂度为O(n²);而使用HashMap的方法虽然减少了循环次数,但查找value仍然需要额外时间。

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

题目链接:https://leetcode.com/problems/two-sum/#/description

遍历问题

暴力解法:遍历数组,算法复杂度O(n²)

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] test = {0,0};
        for(int i = 0 ; i < nums.length ; ++i) 
        {
            for(int j = i+1 ; j < nums.length ; ++j)
            {
                if( target == (nums[i] + nums[j]) )
                {
                    test[0] = i;
                    test[1] = j;
                    return test;
                }
            }
        }
        return test;
    }
}

hashMap:虽然少了一次循环,但是HashMap的查找value值仍需要额外的时间

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        if (nums == null || nums.length < 1) 
            return new int[]{-1, -1};
        
        HashMap<Integer, Integer> test = new HashMap<Integer, Integer>();
        for(int i = 0 ; i < nums.length ; ++i)
        {
            int complement = target-nums[i];
            if(test.containsKey(complement))
            {
                return new int[]{test.get(complement), i};
            }
            else
            {
                test.put(nums[i], i);
            }
        }
        return new int[]{-1, -1};
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值