1. Two Sum

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容器中元素进行操作,需要哈希表(这里指的是无关联容器)作为缓存容器的算法,哈希表是很好的中介!
给定一个整数数组 nums 和一个目标值 target,要求在数组中找出两个数的和等于目标值,并返回这两个数的索引。 思路1:暴力法 最简单的思路是使用两层循环遍历数组的所有组合,判断两个数的和是否等于目标值。如果等于目标值,则返回这两个数的索引。 此方法的时间复杂度为O(n^2),空间复杂度为O(1)。 思路2:哈希表 为了优化时间复杂度,可以使用哈希表来存储数组中的元素和对应的索引。遍历数组,对于每个元素nums[i],我们可以通过计算target - nums[i]的值,查找哈希表中是否存在这个差值。 如果存在,则说明找到了两个数的和等于目标值,返回它们的索引。如果不存在,将当前元素nums[i]和它的索引存入哈希表中。 此方法的时间复杂度为O(n),空间复杂度为O(n)。 思路3:双指针 如果数组已经排序,可以使用双指针的方法来求解。假设数组从小到大排序,定义左指针left指向数组的第一个元素,右指针right指向数组的最后一个元素。 如果当前两个指针指向的数的和等于目标值,则返回它们的索引。如果和小于目标值,则将左指针右移一位,使得和增大;如果和大于目标值,则将右指针左移一位,使得和减小。 继续移动指针,直到找到两个数的和等于目标值或者左指针超过了右指针。 此方法的时间复杂度为O(nlogn),空间复杂度为O(1)。 以上三种方法都可以解决问题,选择合适的方法取决于具体的应用场景和要求。如果数组规模较小并且不需要考虑额外的空间使用,则暴力法是最简单的方法。如果数组较大或者需要优化时间复杂度,则哈希表或双指针方法更合适。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值