zoukankan      html  css  js  c++  java
  • 3Sum

    Given an array S of n integers, are there elements abc 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, a ≤ b ≤ c)
    • 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)
    class Solution {
    public:
        int b_search(vector<int> &n, int b, int e, int x) {
            int l = b;
            int r = e;
            while (l <= r) {
                int mid = l + ((r - l ) >> 2);
                if (n[mid] == x) {
                    return mid;
                } else if (n[mid] > x) {
                    r = mid - 1;
                } else {
                    l = mid + 1;
                }
            }
            return -1;
        }
        /*
         *固定其中2点,找第3点,如果找到就添加到结果中
         * 每次固定左边的点,从右想走遍历右边的点,查找两个点的之间是否有满足的点
         * 注意左边的点要去掉重复的
         */
        vector<vector<int>> threeSum(vector<int>& nums) {
            int i,j,k;
            int size = nums.size();
            vector<vector<int>> res;
            sort(nums.begin(), nums.end());
            for (i=0; i<size-2; i++) {
                //过滤掉相同的左边点,防止出现重复的结果
                if (i > 0 && nums[i] == nums[i-1]) {
                    continue;
                }
                for (j=size-1; j>i+1; j--) {
                    if (j < size-1 && nums[j] == nums[j+1]) {
                        continue;
                    }
                    int s = b_search(nums, i+1, j-1, 0 - nums[i] - nums[j]);
                    if (s != -1) {
                        vector<int> tmp;
                        tmp.push_back(nums[i]);
                        tmp.push_back(nums[s]);
                        tmp.push_back(nums[j]);
                        res.push_back(tmp);
                    }
                }
            }
            return res;
        }
    };
  • 相关阅读:
    STM32学习笔记之__attribute__ ((at())绝对定位分析
    CRC 自动判断大端 小端
    AT命令控制上网 PDP
    PPP PDP 及GPRS
    Renesas CAT CONFIG
    AT指令(二)
    字节对齐问题
    IntelliJ Idea 常用快捷键列表
    solr6.6 导入 文本(txt/json/xml/csv)文件
    solr6.6 导入 pdf/doc/txt/json/csv/xml文件
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5097467.html
Copyright © 2011-2022 走看看