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

法I:先快速排序,时间复杂度O(nlogn),然后再二分法查找,时间发杂度O(nlogn)。这样比乱序时查找O(n2)要快。

struct MyStruct {
int data;
int pos;
MyStruct(int d, int p){
data = d;
pos = p;
}
bool operator < (const MyStruct& rf) const{//参数用引用:避免占用过大内存,并且避免拷贝;用const防止改变操作数
if(data < rf.data) return true;
else return false;
}
};
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<MyStruct> myNums;
vector<int> ret;
int idx1 = , idx2;
for(int i = ; i < nums.size(); i++){
MyStruct* num = new MyStruct(nums[i],i);
myNums.push_back(*num);
} sort(myNums.begin(),myNums.end());
while(!binarySearch(myNums, target-myNums[idx1].data, idx1+, nums.size()-, idx2)){
idx1++;
} ret.clear();
if(myNums[idx1].pos < idx2){
ret.push_back(myNums[idx1].pos+);
ret.push_back(idx2+);
}
else{
ret.push_back(idx2+);
ret.push_back(myNums[idx1].pos+);
}
return ret;
} bool binarySearch(const vector<MyStruct>& nums, const int& target, int start, int end, int& targetPos)
{
if(end - start == ){
if(nums[start].data == target){
targetPos = nums[start].pos;
return true;
}
else if(nums[end].data == target){
targetPos = nums[end].pos;
return true;
}
else return false;
} int mid = (start + end) >> ;
if(nums[mid].data == target){
targetPos = nums[mid].pos;
return true;
} if(nums[mid].data > target && start != mid && binarySearch(nums, target, start, mid, targetPos)) return true;
if(binarySearch(nums, target, mid, end, targetPos)) return true; return false;
}
};

法II:hash table. unordered_map的内部实现是先将key通过hash_value()得到其hash值,相同hash值的key以红黑树排列,查找时间是O(logn),建树的时间类似建大顶堆,时间复杂度是O(n)

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ret;
unordered_map<int,int> map;
unordered_map<int,int>::iterator it; for(int i = ; i < nums.size(); i++){
it = map.find(target-nums[i]);
if(it!=map.end()){
ret.push_back(it->second);
ret.push_back(i);
return ret;
} map.insert(make_pair(nums[i],i));
}
return ret;
}
};

1.Two Sum (Array; HashTable)的更多相关文章

  1. Group and sum array of hashes by date

    I have an array of hashes like this: [{:created=>Fri, 22 Jan 2014 13:02:13 UTC +00:00, :amount=&g ...

  2. Two Sum(hashtable)

    Given an array of integers, find two numbers such that they add up to a specific target number. The ...

  3. 1. Two Sum [Array] [Easy]

    Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...

  4. 36. Valid Sudoku (Array; HashTable)

    Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could be ...

  5. LeetCode 548. Split Array with Equal Sum (分割数组使得子数组的和都相同)$

    Given an array with n integers, you need to find if there are triplets (i, j, k) which satisfies fol ...

  6. [LeetCode] Nested List Weight Sum II 嵌套链表权重和之二

    Given a nested list of integers, return the sum of all integers in the list weighted by their depth. ...

  7. Scala入门之Array

    /** * 大数据技术是数据的集合以及对数据集合的操作技术的统称,具体来说: * 1,数据集合:会涉及数据的搜集.存储等,搜集会有很多技术,存储现在比较经典的是使用Hadoop,也有很多情况使用Kaf ...

  8. [CareerCup] 18.12 Largest Sum Submatrix 和最大的子矩阵

    18.12 Given an NxN matrix of positive and negative integers, write code to find the submatrix with t ...

  9. Leetcode: Max Sum of Rectangle No Larger Than K

    Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix s ...

随机推荐

  1. js如何获取数字占的位数~

    获取整数的长度可以用以下几种方法实现: 1.调用toString方法转为字符串后取长度 var num = 123; alert(num.toString().length); 2.隐式转字符串后取长 ...

  2. Access-Control-Allow-Origin 跨域问题

    1.同源.同源策略(Same origin policy) 同源指的是协议,端口,域名全部相同. 同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺 ...

  3. 手贱,写个call玩玩.

    今天在睡觉醒时,突然感觉对call和apply有了点理解,但是又不好表达出来.就随便写几个例子. function say() { return this.role; } function Fathe ...

  4. 第13章 TCP编程(2)_TCP的连接和关闭过程

    4. TCP的连接和关闭过程 4.1 TCP连接的三次握手和四次挥手 (1)三次握手 ①第1次握手:建立连接.客户端发送连接请求报文段(SYN=1,sequence Number=x):然后客户端进入 ...

  5. 开发组件:Systemd

    Systemd 入门教程:命令篇 http://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-commands.html

  6. 关于tcp的三次握手与四次挥手,以及粘包

    tcp三次握手: TCP是因特网中的传输层协议,使用三次握手协议建立连接.当主动方发出SYN连接请求后,等待对方回答SYN+ACK[1],并最终对对方的 SYN 执行 ACK 确认.这种建立连接的方法 ...

  7. hdu 4370 0 or 1,最短路

    题目描述 给定n * n矩阵C ij(1 <= i,j <= n),我们要找到0或1的n * n矩阵X ij(1 <= i,j <= n). 此外,X ij满足以下条件: 1. ...

  8. 在Apache下开启SSI配置

    开启SSI:html.shtml页面include网页文件 使用SSI(Server Side Include)的html文件扩展名,SSI(Server Side Include),通常称为&quo ...

  9. ABAP-BarCode-1-HTML二维码打印及动态屏幕实现

    很久很久...以前写的一个测试程序,主要是通过ABAP与HTML交互,编写JavaScript实现二维码及动态屏幕实现. 1.ABAP界面效果 2.实现代码 *&--------------- ...

  10. C#--反射技术

    反射:反射为了动态(比如动态的加载dll,动态创建类型.动态调用方法等) 引用 using System.Reflection 原理: 一个类库编译后会生成一个以.dll结尾的文件,一个以.pdb结尾 ...