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. 关于String.valueOf()和.toString的问题

    以下是String.valueOf()的源代码 public static String valueOf(Object obj) {     return (obj == null) ? " ...

  2. shell 1基础

    shell简介 shell是一个用C语言编写的程序,是用户使用Linux的桥梁.shell既是一种命令语言,又是一种程序设计语言. shell脚本(shell script),是一种为shell编写的 ...

  3. 【H3C交换机】cpu各个进程的详细说明

    display cpu-usage命令用来查看设备CPU占用率的统计信息,以及各个进程的cpu占用率. 各个进程详细说明如下,不同软件版本.盒式和框式的cpu进程略有不同,详细信息可以查看手册中的命令 ...

  4. Oracle内存详解之二 Library cache 库缓冲-转载

    Library cache是Shared pool的一部分,它几乎是Oracle内存结构中最复杂的一部分,主要存放shared curosr(SQL)和PLSQL对象(function,procedu ...

  5. Out 与 Ref 关键字的区别

    相同点:既可以通过值也可以通过引用传递参数.通过引用传递参数允许函数成员更改参数的值,并保持该更改.若要通过引用传递参数, 可使用ref或out关键字.ref和out这两个关键字都能够提供相似的功效, ...

  6. 尝试了一些时间,最简单的apache上设置用IP访问一个虚拟目录

    就是其实新建一个 多域名访问的设置 <VirtualHost *:80> DocumentRoot /var/www/ ServerName IP</VirtualHost> ...

  7. OpenACC 与 CUDA 的相互调用

    ▶ 按照书上的代码完成了 OpenACC 与CUDA 的相互调用,以及 OpenACC 调用 cuBLAS.便于过程遇到了很多问题,注入 CUDA 版本,代码版本,计算能力指定等,先放在这里,以后填坑 ...

  8. 《内存数据库和mysql的同步机制》

    如下图  

  9. DBCP连接池配置常用参数说明

    参数 默认值 说明 username \ 传递给JDBC驱动的用于建立连接的用户名 password \ 传递给JDBC驱动的用于建立连接的密码 url \ 传递给JDBC驱动的用于建立连接的URL ...

  10. 红帽yum源安装报错initscripts-9.49.41-1.el7.x86_64 conflicts redhat-release &lt; 7.5-0.11" ?

    https://access.redhat.com/solutions/3425111 环境 Red Hat Enterprise Linux 7 问题 yum fails to apply upda ...