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