1.Two Sum (Array; HashTable)
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)的更多相关文章
- 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 ...
- Two Sum(hashtable)
Given an array of integers, find two numbers such that they add up to a specific target number. The ...
- 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 ...
- 36. Valid Sudoku (Array; HashTable)
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could be ...
- 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 ...
- [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. ...
- Scala入门之Array
/** * 大数据技术是数据的集合以及对数据集合的操作技术的统称,具体来说: * 1,数据集合:会涉及数据的搜集.存储等,搜集会有很多技术,存储现在比较经典的是使用Hadoop,也有很多情况使用Kaf ...
- [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 ...
- 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 ...
随机推荐
- 6.后台验证码-session作用域
首先要有生成验证码图片和验证码文字的逻辑 package cn.bingou.util; import java.awt.Color; import java.awt.Font; import jav ...
- 更喜欢从一而终?bing测试在新窗口打开链接遭美国网友痛批
原链接地址:http://www.cnbeta.com/articles/186529.htm 我们都知道在中国网站点击一个链接之后,默认在新窗口或新标签打开,大家也很熟悉 ...
- [UE4]封装、继承、多态
面向对象编程的三大特征 一.封装 公开能做什么,隐藏如何做.封装的目的是减少类之间的依赖. 二.继承 让一个类拥有另一个类的状态和行为,前者可以不加修改地完全复用后者的实现,也可以对有些行为做出自己的 ...
- php实现socket
一.Socket 简介 1.socket只不过是一个数据结构. 2.使用这个socket数据结构去开始一个客户端和服务器之间的会话. 3.服务器是一直在监听准备产生一个新的会话.当一个客户端连接服务器 ...
- centos安装jdk1.7.80的rpm包
1.jdk1.7.80的rpm的包的下载地址如下,请自己选择32位还是64位,下载完之后通过vmware的共享功能共享一个文件下,然后使用cp命令copy到linux系统中去. http://www. ...
- 在控制终端输入AT命令
控制台终端输入AT命令到smd8,步骤如下: 1. 先执行命令 cat /dev/smd8 & 2. 再执行 echo -e "ati\r\n" > /dev ...
- UVA439-水题
题意:一只棋盘上的马,从一个点到另外一个点要走多少步 解法:广搜 #include<stdio.h> #include<iostream> #include <strst ...
- 怎么理解Linux软中断?
1.什么是中断 中断是系统用来响应硬件设备请求的一种机制,它会打断进程的正常调度和执行,然后调用内核中的中断处理程序来响应设备的请求. 2.为什么要有中断呢? "举个生活中的例子" ...
- 代码:css小图标
向下小箭头 .icon-tip{ border-color: transparent transparent #bb0808 transparent; border-style:solid; bord ...
- 学习笔记:Zepto笔记
1.Zepto对象不能自定义事件 例如执行:$({}).bind('cust',function(){}); 结果:TypeError:Object#hasnomethod'addEventListe ...