01Two Sum题解

Tow Sum

原题概述:

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, and you may not use the same element twice.


Example:

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

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


题目大意:

  1. 题目给出一个不一定有序的整型数组和一个数值target。
  2. 在数组中找到两个数加起来 == target,返回其下标。
  3. 题目保证答案只有一个,并且数组中的每个数只能用一次.

解答:

整理一下思路:

要找到两数和为指定数值,如果用双层for循环,那么时间复杂度将会达到O(n)级别。

考虑一种思路:如果数组有序,采用双指针的思想,我们从第一个元素+最后一个元素开始判断。

(1) 如果第一个元素+最后一个元素 > target,那么指向最后一个元素的指针移动到倒数第二个元素。

(2) 如果第一个元素 + 最后一个元素 < target,那么指向第一个元素的指针移动到第二个位置。

(3) 如果正好相等,直接返回。时间复杂度就达到O(n)级别(是在有序的情况下)。但是要让数组有序,利用快排等方法时间复杂度为 nlogn.

附上Accept代码:

class Solution 
{
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        vector<int> vctResult;
        if(nums.size() < 2)
        {
            return vctResult;
        }
        if(nums.size() == 2)
        {
            vctResult.push_back(0);
            vctResult.push_back(1);
            return vctResult;
        }
        
        vector<int> vct(nums.begin(),nums.end());
        sort(vct.begin(),vct.end());
        int iStart = 0, iEnd = nums.size() - 1;
        while(iStart < iEnd)
        {
            if(vct[iStart] + vct[iEnd] == target)
            {
                iStart = vct[iStart];
                iEnd = vct[iEnd];
                break;
            }
            else if(vct[iStart] + vct[iEnd] < target)
            {
                ++iStart;
            }
            else
            {
                --iEnd;
            }
        }
        for(unsigned int i = 0; i < vct.size(); ++i)
        {
            if(nums[i] == iStart)
                vctResult.push_back(i);
            else if(nums[i] == iEnd)
                vctResult.push_back(i);
        }
        return vctResult;
    }
};

猜你喜欢

转载自www.cnblogs.com/love-jelly-pig/p/9595281.html
今日推荐