LeetCode OJ : 1 Two Sum

readyao發表於2015-11-26

Two Sum

Total Accepted:158719Total Submissions:820714Difficulty: Medium

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

這個題目很簡單,不過我首先想到思路很簡單,效率不高。

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

第二種思路也比較容易想到:

因為第一種方法,時間複雜度主要在兩個for迴圈上面,所以如果想降低時間複雜度必須從兩個for迴圈入手;第一個for迴圈應該少不了吧(起碼我目前認為是這樣),第二個for迴圈其實降低它的時間複雜度;因為可以對target-nums[i]的值進行二分查詢,如果能夠找到,則ok;


第三種方法是用STL的演算法find來查詢target-nums[i];不過該演算法的時間複雜度沒有二分查詢低;

下面首先是algorithm中find演算法的實現原始碼:

template<class InputIterator, class T>
  InputIterator find (InputIterator first, InputIterator last, const T& val)
{
  while (first!=last) {
    if (*first==val) return first;
    ++first;
  }
  return last;
}

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> twonum;
        vector<int>::iterator pos1, pos2;
        for(pos1 = nums.begin(); pos1 != nums.end(); ++pos1){
            pos2 = find(pos1+1, nums.end(), target-(*pos1));
            if(pos2 != nums.end()){
                twonum.push_back(pos1-nums.begin()+1);
                twonum.push_back(pos2-nums.begin()+1);
                return twonum;
            }
        }
    }
};

肯定還會有時間複雜度更低的實現演算法,如果知道的話以後再補上;感覺如果使用的查詢演算法好的話,那麼該演算法一定會好;


第一種的執行時間見下圖:


第二種的執行時間如下:


為什麼別人的執行時間都這麼少啊。目前想不到比較好的演算法。以後知道了再更新;

相關文章