167. Two Sum II
来源:互联网 发布:ctr预估 算法融合 编辑:程序博客网 时间:2024/06/03 21:42
题目:
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=2
思路:本题其实很简单,利用两个for循环即可,还有一种O(n)的思路,即利用两个指针从首尾遍历,求和sum,sum==target,返回对应index,sum>target,尾指针左移,sum<target,首指针右移。
代码1(两个for循环):
class Solution {public: vector<int> twoSum(vector<int>& numbers, int target) { int index_t; vector<int> res(0); for(int i=0;i<numbers.size()-1;i++) { if(numbers[numbers.size()-1]<=target) { index_t = numbers.size()-1; break; } if(numbers[i]<=target&&target<=numbers[i+1]) { index_t = i+1; break; } } cout<<index_t<<endl; for(int j = index_t;j>0;j--) { for(int z =0;z<j;z++) { if((numbers[z]+numbers[j])==target) { res.push_back(z+1); res.push_back(j+1); return res; } } } return res; }};
代码2(两个指针):
class Solution {public: vector<int> twoSum(vector<int>& numbers, int target) { int l = 0, r = numbers.size() - 1; while (l < r) { int sum = numbers[l] + numbers[r]; if (sum == target) return {l + 1, r + 1}; else if (sum < target) ++l; else --r; } return {}; }};
阅读全文
1 0
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- 167. Two Sum II
- c++中字符串反转的3种方法
- 获取当前日期的前一天
- ProgressManager 进度监听器
- R语言对爬取的天气数据进行整理
- 小程序server-实现会话层
- 167. Two Sum II
- 火星坐标、百度坐标、WGS84坐标转换代码(JS、python版)
- ubuntu 16.0.4安装Gitblit
- 前后端分离后的前端时代
- WebGL 绘制Line的bug(三)
- SSM框架-SpringMVC 实例文件上传下载
- centos yum安装nginx 提示 No package nginx available问题解决方法
- idea遇到奇葩问题
- Hibernate 所有缓存机制详解