LeetCode 001. Two Sum

題目: 編程

Given an array of integers, find two numbers such that they add up to a specific target number. less

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. spa

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

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2 ci

好像在《編程之美》裏看到過,用hashset.時間複雜度O(N)。 get

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target)
    {
        unordered_set<int> s1(nums.begin(), nums.end());
        for (int index1=0; index1 != nums.size(); ++index1)
        {
            auto pos = s1.find(target-nums[index1]);
            if(pos != s1.end())
            {
                auto pos2 = find(nums.cbegin(), nums.cend(), target-nums[index1]);
                int index2 = pos2-nums.begin();
                if(index1 > index2)
                    swap(index1, index2);
                if(index1 == index2)
                    continue;
                return vector<int>{index1+1, index2+1};
            }
        }
    }
};
相關文章
相關標籤/搜索