[leetcode] 1. Two Sum 解题报告

题目链接:https://leetcode.com/problems/two-sum/

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


思路:这道题有几种解法。

第一种:两重循环搜索所有的情况,我没有试过这种方法,因为时间复杂度是O(n*n),估计是过不了测试数据的。

第二种:将数组排序,然后两个指针从左右分别扫描数组:

1)如果当前和大于target,则右指针左移一位;

2)如果当前和小于target,则左指针右移一位

这种方法需要排序和记录原数组中数的坐标,并且得到的index仍然需要排序放入结果中。比较麻烦。时间复杂度是O(n*log(n)),这是排序的复杂度。

第三种:利用map容器,将原数组中的数放到map中,然后扫描一遍即可,很方便。时间复杂度为O(n*log(n)),将数组依次插入map的时间复杂度是O(n*log(n))。

这种还需要注意的是如果一个数可以分解为两个相同数的和的情况。

下面给出了第二种和第三种解法的代码:

第二种:

class Solution {
public:
    typedef struct Node
    {
        int index;
        int val;
    }Node;
    static bool cmp(const Node& a, const Node& b)
    {
        return a.val < b.val;
    }

    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        if(nums.size() == 0) return result;
        vector<Node> vec;
        for(int i = 0; i< nums.size(); i++)
        {
            Node tem;
            tem.index = i+1;
            tem.val = nums[i];
            vec.push_back(tem);
        }
        sort(vec.begin(), vec.end(), cmp);
        int index1 = 0, index2 = nums.size()-1;
        while(index1 < index2)
        {
            if(vec[index1].val + vec[index2].val == target)
                break;
            if(vec[index1].val + vec[index2].val < target)
                index1++;
            if(vec[index1].val + vec[index2].val > target)
                index2--;
        }
        int a = min(vec[index1].index, vec[index2].index);
        int b = max(vec[index1].index, vec[index2].index);
        result.push_back(a);
        result.push_back(b);
        
        return result;
    }
};


第三种:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        map<int, int> mp;
        for(int i = 0; i< nums.size(); i++)
            mp[nums[i]] = i + 1;
        for(int i = 0; i< nums.size(); i++)
        {
            int val = target - nums[i];
            if(mp.find(val) != mp.end() && mp[val] != i+1)
            {
                result.push_back(i+1);
                result.push_back(mp[val]);
                break;
            }
        }
            
        return result;
    }
};

第三种方法参考:http://fisherlei.blogspot.com/2013/03/leetcode-two-sum-solution.html



你可能感兴趣的:(LeetCode,算法,排序,sort)