关关的刷题日记14——Leetcode 167. Two Sum II - Input array is sorted
关小刷刷题14 – Leetcode 167. Two Sum II - Input array is sorted
题目
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=9Output: index1=1, index2=2
这题与two sum的区别是,数组是按照从小到大的顺序排好序的,参考一下刷题日记11中的两种做法。
方法1
方法1:双重指针,时间复杂度O(n)。对于排好序的数组这种方法非常好!
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int i=0, j=numbers.size()-1;
vector<int>output(2,0);
while(true)
{
int sum=numbers[i]+numbers[j];
if(sum>target)
j--;
else if(sum<target)
i++;
else
{
output[0]=i+1;
output[1]=j+1;
break;
}
}
return output;
}
};
方法2
方法2:哈希表,时间复杂度O(n).
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int>output(2,0);
hash_map<int, int>m;
for(int i=0; i<numbers.size(); i++)
{
if(m.find(target-x)!=m.end())
m[x]=i+1;
else
{
output[0]=min(m[x], m[target-x]);
output[1]=max(m[x], m[target-x]);
break;
}
}
return output;
}
};
只有非常努力,才能看起来毫不费力,加油!
以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- Pandas重复值处理
- Pandas缺失值处理
- Pandas分类数据和顺序数据转换为标志变量
- 使用ProxyBroker构建代理池
- 国内pypi镜像
- [已解决]Series object has no attribute explode
- 2019年Pandas官方用户调研
- 刚刚!程序员用力过猛,燃起来了!
- VSCode 中文乱码
- Python获取时间戳
- VScode Python no module的解决方法
- MacOS安装npm全局包的权限问题
- [已解决]报错run `npm audit fix` to fix them, or `npm audit` for details
- Hexo使用攻略-添加分类及标签
- print的简单使用