博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Two Sum(leetcode1)
阅读量:5968 次
发布时间:2019-06-19

本文共 1003 字,大约阅读时间需要 3 分钟。

 

Given an array of integers, 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.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

 

1 public class Solution { 2     public int[] twoSum(int[] nums, int target) { 3         HashMap
hm = new HashMap
(); 4 for(int i = 0; i < nums.length; i++){ 5 Integer diff = (Integer)(target - nums[i]); 6 if(hm.containsKey(diff)){ 7 int result[] = {hm.get(diff)+1, i+1}; 8 return result; 9 }10 hm.put(nums[i], i);11 }12 return null;13 14 }15 }

转载于:https://www.cnblogs.com/caomeibaobaoguai/p/4873501.html

你可能感兴趣的文章
php正则怎么使用(最全最细致)
查看>>
javascript数学运算符
查看>>
LC.155. Min Stack(非优化,两个stack 同步 + -)
查看>>
交互设计[3]--点石成金
查看>>
SCCM TP4部署Office2013
查看>>
Android创建启动画面
查看>>
Linux中date命令的各种实用方法--转载
查看>>
mysqld -install命令时出现install/remove of the service denied错误的原因和解决办法
查看>>
苹果企业版帐号申请记录
查看>>
C++ Error: error LNK2019: unresolved external symbol
查看>>
Bitmap 和Drawable 的区别
查看>>
Java操作mongoDB2.6的常见API使用方法
查看>>
如何给服务器设置邮件警报。
查看>>
麦克劳林
查看>>
Eclipse SVN修改用户名和密码
查看>>
架构师的职责都有哪些?
查看>>
SVN: bdb: BDB1538 Program version 5.3 doesn't match environment version 4.7
查看>>
jsp内置对象作业3-application用户注册
查看>>
android115 自定义控件
查看>>
iOS uuchart 用法
查看>>