1. Two Sum

来源:互联网 发布:部落冲突 法师升级数据 编辑:程序博客网 时间:2024/05/17 07:50

Two Sum Problem Definition


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

You may assume that each input would have exactly one solution.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

UPDATE (2016/2/13):

The return format had been changed to zero-based indices. Please read the above updated description carefully.

Two Sum Problem Analysis


题目要求返回整型数组中两个元素相加和等于target的元素的下标数组;题目假设每个输入有unique solution.

Brute Force, 时间复杂度为 O(N^2)

很容易想到的方法,两个for循环进行比较,不过时间复杂度很高,当数组元素很大很大时候,效果不好。

代码如下:

class Solution {public:    vector<int> twoSum(vector<int> &nums, int target) {        vector<int> coll;        for (int i = 0; i < nums.size() - 1; ++i) {            for (int j = i + 1; j < nums.size(); ++j) {                if (nums[i] + nums[j] == target) {                    coll.push_back(i);                    coll.push_back(j);                    break;                }            }        }        return coll;     }};

Sort Method,时间复杂度为 O(NlogN)

sorting the input gives the array a good property to keep and good indication for moving the head and tail pointers.
[http://www.sigmainfy.com/blog/two-sum-problem-analysis-1-sort-hash-unique-solution.html]

Here is the detailed steps.

  1. Sort the input in increasing order
  2. make two pointers i, j pointing at the head and tail elements of the sorted array
  3. by comparing the related order between the target and the sum of the two elements pointed by the current head/tail pointers, we decide how to move the pointers to test next (copyright @sigmainfy) potential pairs
  4. If the target is bigger, we move the head pointer forward by one step and thus try to increase the sum, if the target is smaller we move the tail head towards the head by one step and thus try to decrease the sum a bit, if target is equal to the sum, then we are done by the assumption that there is only one such pair
  5. we repeat step 3 and 4 until i >= j or we find a solution

So as we could see, the time complexity for this approach would be O(NlogN). The following is the source code which is acccepted by leetcode OJ for your reference:

vector<int> TwoSum(vector<int> &numbers, int target) {    vector<int> idxes(2, -1);    vector<pair<int, int>> number_structs;    int len = numbers.size();    for (int i = 0; i < len; ++i)        number_structs.push_back(make_pair(numbers[i], i));    sort(number_structs.begin(), number_structs.end());    int i = 0, j = number_structs.size() - 1, sum = 0;    while (i < j) {        sum = number_structs[i].first + number_structs[j].first;        if (sum < target) ++i;        else if (sum > target) --j;        else {            int reali = number_structs[i].second + 1, realj = number_structs[j].second + 1;            idxes[0] = min(reali, realj);            idxes[1] = max(reali, realj);            break;        }    }    return idxes;}

另外,下面的博客的可以学习一下

http://www.cnblogs.com/mickole/p/3695894.html
http://www.cnblogs.com/pengzheng/archive/2013/05/12/3074624.html

Hash Table Method,时间复杂度线性为O(N)

★ Why unordered_map

    class Solution {    public:        vector<int> twoSum(vector<int>& nums, int target) {            vector<int> coll(2, -1);        // 存放返回vector的元素,只需要返回两个值,初始化两个初值            unordered_map<int, int> u_map;  // 作为nums的缓存容器,方便查找            int len = nums.size();            // 把nums中元素赋值给无序关联容器map中            for(int i = 0; i < len; ++i){                u_map[nums[i] ] = i;// first(键key)存放的是nums的元素值; second(值value)存放的是nums的下标i            }            for(int i = 0; i < len; ++i){                // 利用unordered_map的成员函数find查找,返回查找到的第一个元素的位置                auto pos = u_map.find(target - nums[i]);// key value,查找的是value                // 找到                if(pos != u_map.end()){                    if(pos->second <= i)                        continue;                    // vector<int> coll(2, -1);  //vector<int> coll                    coll[0] = i;                 // coll.push_back(i);                    coll[1] = pos->second;       // coll.push_back(pos->second);                    break;                }            }            return coll;        }    };

自己刚开始写的一种很杂乱的方法(可行),时间复杂度线性

方法可行,但暴露了一些问题!

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int> coll;        int temp;        for(auto it = nums.begin(); it!=nums.end(); ++it){            temp = target - *it;            auto pos = find(it+1, nums.end(), temp);            if(pos != nums.end()){                int jtemp = pos - nums.begin();                int itemp = it - nums.begin();// 注意:下标和迭代器不是一个概念!!!                coll.push_back(itemp); // 不能插入迭代器啊!!!                coll.push_back(jtemp);                         }            return coll;        }    }};

Conlusion


  1. 迭代器和数组的下标不是一个概念!
  2. 同是无序容器,以哈希表实现,unordered_map和unordered_set的不同点有哪些?!
  3. vector可以随机访问,unordered_set不可以随机访问,即没有下标[]访问,支持迭代器访问,但unordered_map是怎么访问元素的,它有什么方便的地方?(用到了”->” 或”.” 和first,second或者[], at)
  4. 经常遇到对vector容器中元素进行操作,需要哈希表(这里指的是无关联容器)作为缓存容器的算法,哈希表是很好的中介!
0 0
原创粉丝点击