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 ...
随机推荐
- unity shader学习笔记(1) shader基础结构以及Properties面板
首先是shader的基础结构: Shader "Custom/Example { Properties//变量属性面板 { } SubShader { Tags { "Render ...
- iOS 蓝牙功能 bluetooth
现将创建蓝牙工程的要点总结一下,由于工程主要涉及中心模式,所以只总结中心模式的用法 1,引入CoreBluetooth.framework 2,实现蓝牙协议,如: .h文件如下 @protocol C ...
- JSP具体篇——application
application对象 application对象用于保存全部应用程序中的共同拥有数据.它在server启动时自己主动创建.在server停止时自己主动销毁. 当application对象没有被销 ...
- Linux下文件的基本操作
文件的基本操作 新建和删除文件夹 命令#mkdir /file 在当前目录创建file文件夹 命令#rmdir /file 删除当前目录下file文件夹 复制和移动文件 命令#cp text/file ...
- [Android]豆瓣FM离线数据
离线目录结构: /sdcard/Android/data/com.douban.radio下 ./cache/fileCaches: 离线音乐歌词(lyric) ./cache/images: 离线音 ...
- A vectorized example
http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture4.pdf
- vue v-on命令
<!-- 阻止单击事件冒泡 --> <a v-on:click.stop="doThis"></a> <!-- 提交事件不再重载页面 ...
- Java找出一组数字的最大值
形如:int [] nums = {7,2,8,9,1,12}; 解一:两两比较并记录下标,下次比较拿上次比较的最大值和上次比较的下一个进行比较,循环一次找出最大值 /** * @author 马向峰 ...
- [Java面试一]Spring总结以及在面试中的一些问题.(转发:http://www.cnblogs.com/wang-meng/p/5701982.html)
1.谈谈你对spring IOC和DI的理解,它们有什么区别? IoC Inverse of Control 反转控制的概念,就是将原本在程序中手动创建UserService对象的控制权,交由Spri ...
- MVC ViewBag不能使用在工程文件中添加引用
在工程文件中 <ItemGroup> // ... </ItemGroup> 添加引用 <Reference Include="Microsoft.CSharp ...