码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode 15] 3Sum

时间:2015-03-01 20:55:04      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

算法渣,现实基本都参考或者完全拷贝[戴方勤(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).

[LeetCode 15] 3Sum

标签:

原文地址:http://www.cnblogs.com/Azurewing/p/4307549.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!