vector<vector<int> > fourSum(vector<int> &num, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function if (num.size() < 4) return result; //O(n ^ 2) v.clear(); result.clear(); for (size_t i = 0; i < num.size(); ++i) { for (size_t j = i + 1; j < num.size(); ++j) { TwoSum t; t.value = num[i] + num[j]; t.pos1 = i; t.pos2 = j; v.push_back(t); } } //O(n ^ 2 log (n ^ 2)) sort(v.begin(), v.end(), my_compare); //O(n) cut_the_tail(target); for (size_t i = 0; i < v.size(); ++i) { //O(log (n ^ 2)) size_t begin = my_binary_search_begin(target - v[i].value, i + 1, v.size() - 1); //reduce the running time size_t end = my_binary_search_end(target - v[i].value, i + 1, v.size() - 1); //reduce the running time //O(n ^ 2) for (size_t j = begin; j <= end; ++j) { if (v[i].pos1 == v[j].pos1 || v[i].pos2 == v[j].pos1 || v[i].pos1 == v[j].pos2 || v[i].pos2 == v[j].pos2) //v[m] and v[n] share a same element continue; else { vector<int> temp; temp.push_back(num[v[i].pos1]); temp.push_back(num[v[i].pos2]); temp.push_back(num[v[j].pos1]); temp.push_back(num[v[j].pos2]); sort(temp.begin(), temp.end()); if (find(result.begin(), result.end(), temp) == result.end()) result.push_back(temp); } } } return result; }
static void RandInts( vec_int& ints, // out: scrambled integers in range 0 ... NSIZE(ints)-1 int seed) // in: random seed { const int n = NSIZE(ints); CV_Assert(n > 0); if (n > RAND_MAX) Err("vector size %d is too big (max allowed is %d)", n, RAND_MAX); CV_Assert(seed != 0); if (seed == 1) // 1 has a special meaning which we don't want seed = int(1e6); // arb int i; for (i = 0; i < n; i++) ints[i] = i; srand(seed); // We use our own random shuffle here because different compilers // give different results which messes up regression testing. // (I think only Visual C 6.0 is incompatible with everyone else?) // // Following code is equivalent to // random_shuffle(ints.begin(), ints.end(), // pointer_to_unary_function<int,int>(RandInt)); vec_int::iterator it = ints.begin(); for (i = 2; ++it != ints.end(); i++) iter_swap(it, ints.begin() + rand() % n); }
void monomial_mul(const vec_int &A, const vec_int &B, vec_int &C) { auto a = A.begin(); auto b = B.begin(); auto c = C.begin(); for (; a != A.end(); ++a, ++b, ++c) { *c = *a + *b; } }