题目:

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

思路:

  首先对数组排序。不过由于最后返回两个数字的索引,所以需要事先对数据进行备份。然后采用2个指针l和r,分别从左端和右端向中间运动:当l和r位置的两个数字之和小于目标数字target时,r减1;当l和r位置的两个数字之和大于目标数字target时,l加1。因此只需扫描一遍数组就可以检索出两个数字了。最后再扫描一遍原数组,获取这两个数字的索引。

 var twoSum = function(nums, target) {
var temp=[];
var index=[];
for(var i=0;i<nums.length;i++){
temp[i]=nums[i];
}
temp.sort(function(a,b){return a-b;}); var l=0,r=temp.length-1; while(l<r){
if(temp[l]+temp[r]==target){
break;
}else if(temp[l]+temp[r]>target){
r--;
}else{
l++;
}
} for(var i=0,n=2;i<nums.length;i++){
if(nums[i]==temp[l]||nums[i]==temp[r]){
index.push(i+1);
--n;
if(n==0){
break;
}
}
} return index;
};

最新文章

  1. c#进阶之神奇的CSharp
  2. MFC 按钮如何改变颜色
  3. Socket编程注意接收缓冲区大小
  4. 《DON&#39;T MAKE ME THINK》/《点石成金访客至上的网页设计秘笈》 读书笔记
  5. Android驱动调试利器Busybox之初体验
  6. iOS-Auto property synthesis will not synthesize property &#39;delegate&#39;; it will be implemented by its super
  7. UIMenuController/UIPasteboard(2) UITableView上实用剪贴板
  8. 一键分享到新浪微博、腾讯微博、搜狐微博、人人网、开心网、百度收藏等js代码大全
  9. kv_storage.go
  10. re模块正则表达式
  11. vue_ajax 请求
  12. Perl正则表达式超详细教程
  13. 设计模式のAbstractFactory(虚拟工厂)----创建模式
  14. select * from dim.dim_area_no@to_dw
  15. input默认显示当前时间
  16. MySQL存储过程中使用SELECT …INTO语句为变量赋值
  17. 远程服务器git搭建
  18. 更改datatables的分页切换时的&#39;processing&#39;提示信息的式样
  19. Docker 拷贝文件
  20. Linux 下的多线程下载工具 Axel

热门文章

  1. IntentService介绍
  2. Android-Sqlite-SQL操作增删改查
  3. 连接池--sp_reset_connection
  4. linux学习之用户的切换
  5. MaxScript镜像函数
  6. Message Loop 原理及应用
  7. GO学习笔记 - 数据类型推导
  8. java学习笔记—ServletConfig、ServletContext接口(13)
  9. 2018-2019-2 20165219《网络对抗技术》Exp2 后门原理与实践
  10. SpringMVC常用方法大全