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 ...
随机推荐
- eclipse 导入maven 父子项目
你先要确认svn上是否是maven项目,否则要自己重新建一个maven项目然后直接引入目录了.如果确认是maven项目,那么有个两个方案.案一:先用任何client软件将svn下载.然后在eclips ...
- saltstack之软件管理
1.installed安装软件包 例: 安装NFS /srv/salt/pkg/nfs.sls nfs: pkg.installed: - pkgs: - nfs-utils 在命令行执行如下 sal ...
- Android创建library工程
本文着重介绍如何创建Android library,并且在工程中使用此library提供的资源,具体步骤如下:1. 创建一个Android工程,命名为sourceProj2. 右键--properti ...
- hdu 3549 Flow Problem【最大流增广路入门模板题】
题目:http://acm.hdu.edu.cn/showproblem.php?pid=3549 Flow Problem Time Limit: 5000/5000 MS (Java/Others ...
- 九度OJ 1262:Sequence Construction puzzles(I)_构造全递增序列 (DP)
时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:118 解决:54 题目描述: 给定一个整数序列,请问如何去掉最少的元素使得原序列变成一个全递增的序列. 输入: 输入的第一行包括一个整数N( ...
- What is the difference between iterations and epochs in Convolution neural networks?
https://stats.stackexchange.com/questions/164876/tradeoff-batch-size-vs-number-of-iterations-to-trai ...
- php自定义函数: 计算两个时间日期相隔的天数,时,分,秒
function timediff( $begin_time, $end_time ) { if ( $begin_time < $end_time ) { $starttime = $begi ...
- Linux开启防火墙后,设置允许通过的端口
安装Firewall命令: yum install firewalld firewalld-config Firewall开启端口命令: firewall-cmd --zone=public --ad ...
- 深入ConcurrentHashMap二
深入ConcurrentHashMap一,已经介绍了主要的ConcurrentHashMap的结构,Segment组成,HashEntry的组成以及包含ConcurrentHashMap的创建. 这篇 ...
- JQuery日记 5.11 Sizzle选择器(五)
//设置当前document和document相应的变量和方法 setDocument = Sizzle.setDocument = function( node ) { var hasCompare ...