zoukankan      html  css  js  c++  java
  • [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偏大,与之前过程中的判断矛盾。

    所以不可能存在。

  • 相关阅读:
    python3删除mysql上月分区数据(脚本)
    ansible之基本原理及命令
    centOS 7 简单设置(虚拟机)
    TCP_Wrappers 简介
    sudo
    引用数据应该选择 ID, CODE 还是 NAME
    吃得洒脱是一种什么体验
    通用数据同步机制
    我的学PyTorch之路(1)
    38岁才学会了游泳的心得
  • 原文地址:https://www.cnblogs.com/Azurewing/p/4307549.html
Copyright © 2011-2022 走看看