栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

1.TwoSum

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

1.TwoSum

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 
                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 map = new HashMap();
        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;
    }
    
}

最后终于提交成功啦!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/988183.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号