LeetCode之Two Sum II - Input array is sorted
发布日期:2021-06-29 14:08:18
浏览次数:2
分类:技术文章
本文共 1228 字,大约阅读时间需要 4 分钟。
1、题目
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2to see which companies asked this question.
2、代码实现
public class Solution { public int[] twoSum(int[] nums, int target) { if (null == nums) return null; int[] result = new int[2]; HashMapmap = new HashMap (); for (int i = 0; i < nums.length; ++i) { Integer value = map.get(nums[i]); if (null == value) map.put(nums[i], i); Integer index = map.get(target - nums[i]); if (null != index && index < i) { result[0] = index + 1; result[1] = i + 1; } } return result; }}
转载地址:https://chenyu.blog.csdn.net/article/details/69810329 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
初次前来,多多关照!
[***.217.46.12]2024年05月01日 12时43分53秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
【Scala 教程】Scala 条件与循环语句
2019-04-29
【Scala 教程】Scala 集合类型
2019-04-29
JAVA 线程同步机制 synchronized
2019-04-29
MySQL 安装教程(无脑版)
2019-04-29
IDEA 怎么删除一个Module
2019-04-29
走进数据科学:最好是通过比网课更好的方法
2019-04-29
AI革命第一步:最容易被忽略但必不可少的物联网
2019-04-29
2020年开发运维工具清单:选择开发运维工具堆栈吧
2019-04-29
效率提升法则:高效人士不会去做的4件事
2019-04-29
8.PostgreSQL约束
2019-04-29
【技术分享】使用AES加密技术保障数据安全
2019-04-29
【应用实例】布线多?成本高?不可靠?泽耀方案没烦恼!
2019-04-29
数据可视化工具:Matplotlib绘图
2019-04-29
用Python写个超级小恐龙跑酷游戏,上班摸鱼我能玩一天
2019-04-29
闺蜜看我用Python画了一幅樱花图,吵着要我给他介绍程序员小哥哥
2019-04-29
【Python爬虫实战】知乎热榜数据采集,上班工作摸鱼两不误,知乎热门信息一网打尽
2019-04-29
Python抓取哔哩哔哩up主信息:只要爬虫学的好,牢饭吃的早
2019-04-29
有个码龄5年的程序员跟我说:“他连wifi从来不用密码”
2019-04-29