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 ...
随机推荐
- centos-linux热拔插scsi硬盘
自己配置虚拟机,需要添加一块虚拟硬盘存放数据.虚拟机在更新软件,不想停机.学习了下热拔插硬盘的知识点 1. 在虚拟机中创建虚拟磁盘并添加. 2. 查看目前的磁盘信息cat /proc/scsi/scs ...
- 牛逼的lsof命令!!!
linux lsof命令详解 简介 lsof(list open files)是一个列出当前系统打开文件的工具.在linux环境下,任何事物都以文件的形式存在,通过文件不仅仅可以访问常规数据,还可以访 ...
- 什么是DSCP,如何使用DSCP标记搭配ROS策略
一.什么是DSCP DSCP:差分服务代码点(Differentiated Services Code Point),IETF于1998年12月发布了Diff-Serv(Differentiated ...
- [UE4]引擎自身提供的无锁队列等无锁容器(TLockFreePointerList)
常用的接口: TLockFreePointerListFIFO<T>:先进先出: TLockFreePointerListLIFO<T>:后进先出: TLockFreePoin ...
- 触屏设备上的多点触碰检测C++代码实现
转自:http://aigo.iteye.com/blog/2272698 代码还是参考自Epic官方的塔防项目:StrategyGame 看了下C++的API,现成的API中貌似只支持单点触碰检测, ...
- Koa 框架整理
学习交流 Koa使用了ES6规范的generator和异步编程是一个更轻量级Web开发的框架,Koa 的先天优势在于 generator.由于是我个人的分享交流,所以Node基础.ES6标准.Web开 ...
- Spark wordcount开发并提交到集群运行
使用的ide是eclipse package com.luogankun.spark.base import org.apache.spark.SparkConf import org.apache. ...
- 初学 python 之 用户登录实现过程
要求编写登录接口 : 1. 输入用户名和密码 2.认证成功后显示欢迎信息 3.用户名输错,提示用户不存在,重新输入(5次错误,提示尝试次数过多,退出程序) 4.用户名正确,密码错误,提示密码错误,重新 ...
- ioi2016aliens
/* 首先考虑点在直线的两边效果一样 于是转移到一边 之后发现当我们覆盖某些点时,有其他的一些点一定会被覆盖 我们找出所有必须覆盖的点 之后我们发现我们找到的这些点 将其按照x递增排序 那么y也是递增 ...
- Java面向对象技术
问题及答案来源自<Java程序员面试笔试宝典>第四章 Java基础知识 4.2面向对象技术 1.面向对象与面向过程有什么区别? 看下面一个实例即可: 面向过程就是分析出解决问题所需要的步骤 ...