Algorithm slag. For details about the reality, refer to or completely copy [Dai fangqin ([email protected])] The leetcode solution of the great god. Here we only record the problem.
Early AC, now TLE
Class solution {public: vector <int> threesum (vector <int> & num) {vector <int> result; If (Num. size () <3) return result; // The sort (Num. begin (), num. end (); // sort 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}); // note that ++ B; -- C ;}} sort (result. begin (), result. end (); result. erase (unique (result. begin (), result. end (), result. end (); return result ;}};
Note:
1. Because the elements are repeated, it is obvious that the above problem cannot be solved by map.
2. function 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 newPast-the-endElement.
3. member function erase
Removes from the vector either a single element (Position) Or a range of elements ([First, last)).
This variable tively has CES 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 completed MED for the same operation by other kinds of sequence containers (such as list orforward_list ).
[Leetcode 15] 3sum