标签:
算法渣,现实基本都参考或者完全拷贝[戴方勤(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
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).
标签:
原文地址:http://www.cnblogs.com/Azurewing/p/4307549.html