1. 程式人生 > >1. Two Sum[ LeetCode ]

1. Two Sum[ LeetCode ]

1. Two 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.


    1. 資料不一定有序,且可能重複,可能為負
    2. 為了提高效率需要空間換時間



    第一種想法是將資料有序化,用struct處理重複資料,再用vector兩頭往中間找
    複雜度 o(nlogn+n)
    缺點:從答案要求上看,"有序+分頭找"的隱含的做了不必要的工作,即排序操作,故並非最佳

class Solution
{
  public:
    vector<int> twoSum(vector<int> &nums, int target);
};
typedef struct bi
{
    int data;
    int pos;
} bi;
bool cmp(const bi &x, const bi &y)
{
    if (x.data <= y.data)
        return true;
    return false;
}
vector<int> Solution::twoSum(vector<int> &nums, int target)
{
    vector<bi> _nums;
    for (vector<int>::size_type i = 0; i < nums.size(); i++)
    {
        bi temp;
        temp.data = nums[i];
        temp.pos = i;
        _nums.push_back(temp);
    }
    sort(_nums.begin(), _nums.end(), cmp);
    /* 之後可以指標兩頭向中間靠攏 */
    vector<int>::size_type i = 0;
    vector<int>::size_type j = _nums.size() - 1;
    while (i <= j)
    {
        int x = _nums[i].data + _nums[j].data;
        if (x == target)
        {
            int _i = _nums[i].pos;
            int _j = _nums[j].pos;
            if (_i > _j)
            {
                _i ^= _j;
                _j ^= _i;
                _i ^= _j;
            }
            vector<int> toReturn({_i, _j});
            return toReturn;
        }
        else if (x > target)
            j--;
        else
            i++;
    }
}

    貼一個答案範例
    複雜度 o(n) [預設find函式的複雜度為線性]

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        std::unordered_map<int, vector<int>::size_type> m;
        for (vector<int>::size_type i = 0; i != nums.size(); ++i) {
            if (m.find(nums[i]) != m.end()) {
                vector<int> res({i, m[nums[i]]});
                return res;
            } else {
                m[target - nums[i]] = i;
            }
        }
        return {};
    }
};
/*
    網上有用bitmap做的,但bitmap不好處理負數:(
    當然,理論上可以用2bitmap來處理...
    或者使用兩個bitmap陣列...
*/