• [LeetCode] 3Sum


    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

    Note:

    • Elements in a triplet (a,b,c) must be in non-descending order. (ie, abc)
    • The solution set must not contain duplicate triplets.
        For example, given array S = {-1 0 1 2 -1 -4},
    
        A solution set is:
        (-1, 0, 1)
        (-1, -1, 2)
    分析:如果使用三层循环的话肯定会Time Limited Exceeded的!
    class Solution {
    public:
        vector<vector<int> > threeSum(vector<int> &num) {
            vector<vector<int> > result;
            int n = (int)num.size();
            if (n > 2) {
                sort(num.begin(), num.end());
    
                for (int i = 1; i < n - 1; ++i) {//序号i为中间的数,序号l为较小的数,序号r为较大的数,每次循环时先固定一个中间的数i
                    if (i > 2 && num[i] == num[i - 2]) 
                        continue;
                    int l = 0, r = n - 1;
                    while (l < i && r > i) {
                        if (l > 1 && num[l] == num[l - 1]) {
                            ++l; 
                            continue;
                        }
                        if (r < n - 1 && num[r] == num[r + 1]) {
                            --r; 
                            continue;
                        }
                        int sum = num[l] + num[i] + num[r];
                        if (sum == 0) {
                            vector<int> item;
                            item.push_back( num[l]);
                            item.push_back( num[i]);
                            item.push_back( num[r]);
                            bool flag = false;
                            for (int j = 0; j < result.size(); ++j) {
                                if (result[j][0] == num[l] && result[j][1] == num[i]) {
                                    flag = true; 
                                    break;
                                }
                            }
                            if (!flag) 
                                result.push_back(item);
                            ++l; 
                            --r;
                        } 
                        else if (sum < 0)
                            ++l; 
                        else 
                            --r;
                    }//end while
                }//end for
            }//end if
            return result;
        }
    
    };
  • 相关阅读:
    记一份电网信息化建设企业信息分析平台规划
    2018年个人心灵历程记录
    OGG For Bigdata To Kafka同步问题处理
    Vue.js有赞商城(思路以及总结整理)
    汉诺塔-递归算法
    git合并分支
    js实现页面消息滚动效果
    chrome实现网页高清截屏(F12、shift+ctrl+p、capture)
    JS计算时间差
    Socket.io详解
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3905581.html
Copyright © 2020-2023  润新知