zoukankan      html  css  js  c++  java
  • Leetcode 15 三数之和

    给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。

    注意:答案中不可以包含重复的三元组。

    示例:

    给定数组 nums = [-1, 0, 1, 2, -1, -4],

    满足要求的三元组集合为:
    [
    [-1, 0, 1],
    [-1, -1, 2]
    ]

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/3sum

    使用双指针,先排序 ,使用一个固定值,另外两个指针i,j分别在在固定值后和结尾,根据大小移动

     1 class Solution {
     2 public:
     3     vector<vector<int>> threeSum(vector<int>& nums) {
     4          vector<vector<int>> res;
     5          vector<int>st;
     6          int len,left,right;
     7          len = nums.size();
     8          if(len<3)
     9            return res;
    10          sort(nums.begin(),nums.end());
    12          
    13          for(int i = 0;i<len;i++)
    14          {
    15              left = i+1;
    16              right = len-1;
    17              int tmp = nums[i];
    18              
    19              if(tmp>0)
    20                  break;
    21              if(i>0&&tmp==nums[i-1])//去除重复值
    22                  continue;
    23              while(left<right)
    24              {
    25 
    26                  int sum = tmp+nums[left]+nums[right];
    27 
    28                     if(sum==0)
    29                    {
    30                        
    31                    vector<int> ss = {tmp,nums[left],nums[right]};
    32                          res.push_back(ss);
    33                        
    34                     while(left<right&&nums[left] == nums[left+1])left++;
    35                     while(left<right&&nums[right]==nums[right-1])right--;
    36                     left++;
    37                     right--;
    38 
    39                     }
    40                     else if(sum>0)
    41                     {
    42                         right--;
    43                     }
    44                     else
    45                     {
    46                         left++;
    47                     }
    48              }
    49              
    50          }
    51         return res;
    52     }
    53 };

    注意不要犯错误  在循环中

    vector<int> st;

     for(int i=0,i<st.size();i++)

    可能循环出错,因为size() 返回的是无符号整型

    建议为

    vector<int> st;

    int len = st.size();

     for(int i=0,i<len;i++)

  • 相关阅读:
    Oracle中查询表中数据的上次更新时间
    数据库分区 分库 分表 分片(转)
    beanFactory和factoryBean的区别(转)
    TCP三次握手形象理解
    深拷贝,浅拷贝(转)
    真的要去做
    '庞然大物'是怎么来的?为何有的技术明明看了很多遍依然不能很好的理解
    java6大原则之单一职责原则,里式替换原则
    状态不好记录一下
    java继承,多态
  • 原文地址:https://www.cnblogs.com/9527s/p/12901002.html
Copyright © 2011-2022 走看看