[Array]167. Two Sum II - Input array is sorted
2024-09-05 22:03:23
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
思路:首先应该注意标题中的关键字,输入的数组已经排序了,也就是说前面是小的数字,后面是大的数字。
自己代码:(从头开始遍历,会超时)
vector<int> twoSum(vector<int>& numbers, int target) {
int n = numbers.size();
vector<int>index;
for(int i = ; i < n - ; i++){
for(int j = i + ; j < n; j++){
if(numbers[i] + numbers[j] == target){
index.push_back(i+);
index.push_back(j+);
}
}
}
return index;
}
优秀代码:(3ms)
vector<int> twoSum(vector<int>& numbers, int target) {
int m = , n = numbers.size() - ;
while(m < n){
if(numbers[m] + numbers[n] < target)
m++;
else if(numbers[m] + numbers[n] > target)
n--;
else
return vector<int>{m + , n + };//这里可以直接返回vector,{}表示赋值初始化
}
}
最新文章
- EasyUI DateTimeBox设置默认时间的注意点
- 2014亚马逊在线笔试题目及解决方案(MMChess问题)
- 迄今最深入、最专业的Hololens评测结果,美国AR大咖艾迪&#183;奥夫曼现身说法
- 【USACO 1.5】SuperPrime Rib
- Redis 的Lua Script脚本功能
- table边框美化
- HTML前端——CSS样式
- java 中遇到的问题及解决方法
- ORA-01013:用户请求取消当前的操作
- IDEA和Eclipse经常使用快捷键(Win Mac)
- bzoj 1778 [Usaco2010 Hol]Dotp 驱逐猪猡(高斯消元)
- Wps的ppt里 让图片按顺序出现 就是点击一下 出现一张照片
- C# 之 Stream 和 byte[] 的相关转换
- Boost Thread学习笔记
- POJ	2062 HDU 1528 ZOJ 2223 Card Game Cheater
- 安全性测试入门:DVWA系列研究(一):Brute Force暴力破解攻击和防御
- SQLServer的三种Recovery Model
- android用OkHttp和okio包通信的坑--气死我了
- DRBD详细解说及配置过程记录
- 主流Linux发行版简介