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 ... 
随机推荐
- [UE4]封装、继承、多态
			面向对象编程的三大特征 一.封装 公开能做什么,隐藏如何做.封装的目的是减少类之间的依赖. 二.继承 让一个类拥有另一个类的状态和行为,前者可以不加修改地完全复用后者的实现,也可以对有些行为做出自己的 ... 
- C++中关于class B:A与Class B::A问题
			一,class B:A为类的继承关系,即A类是B类的基类class <派生类名>:<继承方式><基类名>{<派生类新定义成员>}; 例如: #inclu ... 
- delphi WebBrowser的使用方法详解(三)
			WebBrowser 操作记要 WebBrowser1.GoHome; //到浏览器默认主页 WebBrowser1.Refresh; //刷新 WebBrowser1.GoBack; //后退 ... 
- Jenkins邮件扩展(Email Extension插件 Windows环境)
			1.Jenkins ver. 2.107.3版本自带Email Extension插件启动后即可看到系统设置里的 Extended E-mail Notification ,如果没有请安装 2.安装过 ... 
- python you-get 下载视频
			python使用you-get模块下载视频 pip install you-get # 安装先 怎么用 进入命令行: you-get url 暂停下载:ctrl + c ,继续下载重复 y ... 
- C关键字typedef及argc,argv,env参数含义
			C关键字typedef--为C中各种数据类型定义别名. 在此插一点C知识 int main(int argc,const char *argv[],const char *envp[])主函数的红色部 ... 
- RedHat7.0更新yum源
			https://blog.csdn.net/hongbin_xu/article/details/79316614 
- sssp maven  pom
			pom <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.or ... 
- win10 QQ远程协助部分界面点不了
			win10 QQ远程协助部分界面点不了. 把对方电脑的电脑管家全部退出,退出了也不行. 是win10的防火墙?安全策略? 
- Simple2D-25 精灵动作
			精灵动画作用在精灵上,使精灵表现出动画效果.本文将详细说明如何创建一个简单的动作系统,暂时只有 4 中基本的动作——平移.旋转.缩放和 Alpha 变化,并且这些动作能够自由组合,组成串行动作或并行动 ... 
