1.TwoSum

博主分享了初次尝试LeetCode的Java解题经历,从最初的双重循环解法到采用HashMap优化,提高了算法效率。文章通过两个示例解释了两数之和问题,并提供了两种不同的解决方案,重点讨论了HashMap在解决此类问题中的应用。
摘要由CSDN通过智能技术生成

LeetCode-Java 1.TwoSum

2022-6-22

刚刚学完了Java的基本语法,第一天开始刷LeetCode啦

  1. Two Sum

Easy

336471063Add to ListShare

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have *exactly* one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

看到题目就是想到用两个for循环来求解,,于是:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int res[] = new int[2];
        a1: for (int i = 0; i < nums.length-1; i++)
        {
            for (int j = i+1; j <nums.length ;j++){
                if (nums[i] + nums[j] == target){
                    res[0] = i;
                    res[1] = j;
                    break a1;
                }
            }
        }
        return res;
    }
}

但是这样执行效率并不高,运行时间很长,内存使用还好。百度一下,好像大家都用的hash方法求解的。

然后去看了一下这篇文章(https://blog.csdn.net/xqs196301/article/details/123095920),但是还是对hash table理解不是特别深刻,但是大致了解了一下。可以将要比对的数视为关键字,这样就不必每次循环就进行一次比较,就像是将数组的索引和值对调了一下。下面是用HashMap方法写的代码:


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

最后终于提交成功啦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值