[LeetCode] 3Sum

算法渣,现实基本都参考或者完全拷贝[戴方勤(soulmachine@gmail.com)]大神的leetcode题解,此处仅作刷题记录。

早先AC,现今TLE

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        vector<vector<int> > result;
        if (num.size() < 3)
            return result; // 边界条件判断
        sort(num.begin(), num.end()); // 排序
        const int target = 0;

        auto last = num.end();
        for (auto a = num.begin(); a < prev(last, 2); ++a) {
            auto b = next(a);
            auto c = prev(last);
            int sum = *a + *b + *c;
            while (b < c) {
                if (sum < target) {
                    ++b;
                } else if (sum > target) {
                    --c;
                } else {
                    result.push_back({ *a, *b, *c }); // 注意此时并未结束
                    ++b;
                    --c;
                }
            }
        }
        sort(result.begin(), result.end());
        result.erase(unique(result.begin(), result.end()), result.end());
        return result;
    }
};

 

杂记:

1. 由于元素重复,显然不能以上题map方式解决。

2. 函数unique

Remove consecutive duplicates in range

Removes all but the first element from every consecutive group of equivalent elements in the range [first,last).

The function cannot alter the properties of the object containing the range of elements (i.e., it cannot alter the size of an array or a container): The removal is done by replacing the duplicate elements by the next element that is not a duplicate, and signaling the new size of the shortened range by returning an iterator to the element that should be considered its new past-the-end element.

3. 成员函数erase

Removes from the vector either a single element (position) or a range of elements ([first,last)).
This effectively reduces the container size by the number of elements removed, which are destroyed.
Because vectors use an array as their underlying storage, erasing elements in positions other than the vector end causes the container to relocate all the elements after the segment erased to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list orforward_list).

4. 夹逼正确性

假设序列ABCDEFG,起始时为【A】BCDEDF【G】,若A+G偏小,则【A】处游标需要移动,倘若移动到C处时偏大,则需要移动【G】处游标缩小和,即为AB【C】DE【F】G,倘若C+F依旧偏大,则是是否肯呢过存在C之前的数X,使得X+F满足条件。

倘若存在,且为B,则B+F恰好满足条件,则B+G偏大,与之前过程中的判断矛盾。

所以不可能存在。

posted @ 2015-03-01 20:44  Azurewing  阅读(130)  评论(0编辑  收藏  举报