Two Sum(找出数组中两个和等于指定数字的元素)
2016-01-21 21:21
357 查看
英文:
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.
中文:
给出一组整数,找出其中两个元素,它们的和为我们指定的某个数字,实现函数返回这两个元素从1开始计算的位置,返回值要求第一个数字小于第二个数字。假设给出的数组只有一组解。
例如:给出数组{2, 7, 11, 15},指定的数字是9,则应该返回1和2,因为第一个数字2加上第二个数字7的和是9
从前向后考察数组中各个元素,每查到一个元素,如果HashMap中没有以该元素为键的项,便在HashMap中添加一项,添加的项以指定数字与该元素的差为键,以该数字下标为值;如果HashMap有以该元素为键的项,则将当前位置的下标和HashMap中对应项的值(也是之前存进去的下标),加一后返回
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.
中文:
给出一组整数,找出其中两个元素,它们的和为我们指定的某个数字,实现函数返回这两个元素从1开始计算的位置,返回值要求第一个数字小于第二个数字。假设给出的数组只有一组解。
例如:给出数组{2, 7, 11, 15},指定的数字是9,则应该返回1和2,因为第一个数字2加上第二个数字7的和是9
从前向后考察数组中各个元素,每查到一个元素,如果HashMap中没有以该元素为键的项,便在HashMap中添加一项,添加的项以指定数字与该元素的差为键,以该数字下标为值;如果HashMap有以该元素为键的项,则将当前位置的下标和HashMap中对应项的值(也是之前存进去的下标),加一后返回
相关文章推荐
- 关于对“===”和“==”的思考
- 用AFNetworking实现断点续传,暂停,继续
- 01-SpringMVC Hello,World
- Node利用connect中间件 及bodyParser处理文件上传
- VMware克隆(复制)后网络配置、CentOS设置静态IP、找不到ipv4地址
- java String 类的replace 和replaceAll 方法替换“?”号
- Python实现Logistic 回归实例
- Mac OS安装java runtime环境
- 玩玩三维重建--Visual SFM介绍
- 在linux关机时执行某个脚本
- 用java -X 命令查看JVM的配置说明:
- 十大感动爱情
- Android 高德地图2.80新版地图开发详解(本地定位/地图显示/Mark标记/camera移动和缩放)
- 字节流与字符流的区别详解
- iOS App 性能优化总结
- dp-更难的矩阵取数问题
- OC和Swift中的static
- 2016.01.22 前端学习 HTML/CSS
- OC和Swift中的static
- 点云三维重建--基于两视图的射影重构,仿射重构以及度量重构