leetcode 1 Two Sum(查找)
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
solution:暴力算法很显然是O(n2)会超时。
那么我的做法是把数组排序后二分查找。这样是O(n*lgn)。这里注意一个细节是类内的cmp比较函数要定义成静态成员函数,不然sort调用时会报错:invalid use of non-static member function。因为非静态成员函数是依赖于具体对象的,而std::sort这类函数是全局的,因此无法再sort中调用非静态成员函数。静态成员函数或者全局函数是不依赖于具体对象的, 可以独立访问,无须创建任何对象实例就可以访问。同时静态成员函数不可以调用类的非静态成员。
还有discuss里有更好的O(n)算法,就是hash的思想,利用unordered_map这一无序map来使查找的时间接近常数。unordered_map和map的区别是它无序,所以在不需要排序时最好使用它,比map更快。
class Solution {
public:
struct node{
node(int i,int v):id(i),val(v){}
int id,val;
};
static bool cmp(node a,node b){
return a.val<b.val;
}
vector<int> twoSum(vector<int>& nums, int target) {
vector<node>vt;
vector<int>ans;
vector<int>::iterator it;
int a1=,a2=;
for(it=nums.begin();it!=nums.end();it++){
vt.push_back(node(++a1,*it));
}
sort(vt.begin(),vt.end(),cmp);
a1=;
for(it=nums.begin();it!=nums.end();it++){
int t=*it;
a1++;
a2=lower_bound(vt.begin(),vt.end(),node(,target-t),cmp)-vt.begin();
int a3=upper_bound(vt.begin(),vt.end(),node(,target-t),cmp)-vt.begin();
if(a2<vt.size()&&a2==a3&&vt[a2].val==target-t&&vt[a2].id>a1){
a2=vt[a2].id;
//printf("index1=%d, index2=%d\n",a1,a2);
ans.push_back(a1);
ans.push_back(a2);
return ans;
}
else if(a2<vt.size()&&vt[a2].val==target-t&&a2<a3){/*这个处理很有必要,不然[0,4,3,0]和target=0
这组数据会WA,二分时要注意考虑有几个相等的情况*/
for(int i=a2;i<a3;i++){
if(vt[i].id>a1){
ans.push_back(a1);
ans.push_back(vt[i].id);
return ans;
}
}
}
}
return ans;
}
};
my answer
vector<int> twoSum(vector<int> &numbers, int target)
{
//Key is the number and value is its index in the vector.
unordered_map<int, int> hash;
vector<int> result;
for (int i = ; i < numbers.size(); i++) {
int numberToFind = target - numbers[i]; //if numberToFind is found in map, return them
if (hash.find(numberToFind) != hash.end()) {
//+1 because indices are NOT zero based
result.push_back(hash[numberToFind] + );
result.push_back(i + );
return result;
} //number was not found. Put it in the map.
hash[numbers[i]] = i;
}
return result;
}
better answer in discuss
leetcode 1 Two Sum(查找)的更多相关文章
- [LeetCode] #167# Two Sum II : 数组/二分查找/双指针
一. 题目 1. Two Sum II Given an array of integers that is already sorted in ascending order, find two n ...
- [LeetCode] #1# Two Sum : 数组/哈希表/二分查找/双指针
一. 题目 1. Two SumTotal Accepted: 241484 Total Submissions: 1005339 Difficulty: Easy Given an array of ...
- LeetCode 1 Two Sum 解题报告
LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...
- [LeetCode] 1. Two Sum 两数和
Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...
- [LeetCode] 170. Two Sum III - Data structure design 两数之和之三 - 数据结构设计
Design and implement a TwoSum class. It should support the following operations:add and find. add - ...
- [LeetCode] 653. Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树
Given a Binary Search Tree and a target number, return true if there exist two elements in the BST s ...
- Java for LeetCode 216 Combination Sum III
Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...
- [leetCode][013] Two Sum 2
题目: Given an array of integers that is already sorted in ascending order, find two numbers such that ...
- [array] leetcode - 40. Combination Sum II - Medium
leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...
- [array] leetcode - 39. Combination Sum - Medium
leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without dup ...
随机推荐
- Markdown常用语法学习
Markdown常用语法学习,这些就够用了. 演示地址: https://github.com/YalongYan/Markdown-- 特别提示: 标题'##'后面必须加一个空格,否则编译不对.# ...
- error items-9022:missing required icon file.the bundle does not contain an app icon for iPhone/iPad Touch of exactly '120x120' pixels,in.pen format for ios versions >= 7.0
error items-9022:missing required icon file.the bundle does not contain an app icon for iPhone/iPad ...
- C语言基础知识【数组】
2017年7月11日17:34:05C 数组1.C 语言支持数组数据结构,它可以存储一个固定大小的相同类型元素的顺序集合.数组是用来存储一系列数据,但它往往被认为是一系列相同类型的变量.数组的声明并不 ...
- Elasticsearch集群问题,导致主master节点发现不了node节点
个人博客:https://blog.sharedata.info/ 最新需要配置es集群采用5个分片和1个副片,正好是11台机器,而只保留一份备份所以只需要5*2=10台机器方案:1.1台作为mast ...
- Zabbix 监控tomcat web
个人博客:https://blog.sharedata.info/ 在zabbix监控web,web容器是tomcat 默认的端口是8080导致web监控失败!不能找到主机因此在修改tomcat 端口 ...
- 问题:今天测试模块一直出现一个问题?module 'subprocess' has no attribute 'Popen'
原因:我起的名字用了模块本身的名字,这个地方一定要切记
- python字典中包含列表时:查找字典中某个元素及赋值
直接上代码: 运行效果:
- windows下php升级到7.2
1: 官网下载:https://windows.php.net/download#php-7.2
- vim中设置tab的长度的方法
linux下使用vim编程是比較常见的事情,但vim默认的tab是8个空格.但一般的编辑器是4个空格,所以希望改动下.详细方法例如以下:1. 创建文件名称为 .vimrc 的系统文件首先切换到用户根文 ...
- mysql查询当天,本周,本月,上一个月的数据(转)
今天 select * from 表名 where to_days(时间字段名) = to_days(now()); 昨天 SELECT * FROM 表名 WHERE TO_DAYS( NOW( ) ...