• leetcode 15 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: 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]
    ]

    思路:

    先排序。

    第一种思路:从左往右遍历,将第一个数字和第二个数字固定下来,然后对后面的数字进行二分查找,这样子的时间复杂度是o(n * n * log(n));

    第二种思路:从左往右遍历,只固定第一个数字,然后同时向右和向左移动指针,判断三个数字相加的和是否为0。细节处理在于如果第一个数字重复,则无须再考虑,同时找到一组解之后要忽略掉重复的,注意避免陷入死循环。时间复杂度是o(n * n)。

    代码:

     1 class Solution {
     2 public:
     3     vector<vector<int> > threeSum(vector<int>& nums) {
     4         vector<vector<int> > vec;
     5         sort(nums.begin(),nums.end());
     6         for(int i = 0;i < ((int)nums.size() - 2);i++)
     7         {
     8             if(i > 0 && nums[i] == nums[i - 1])
     9                 continue;
    10             int temp = nums[i];
    11             for(int j = i + 1,k = (int)nums.size() - 1;j < k;)
    12             {
    13                 if(temp + nums[j] + nums[k] == 0)
    14                 {
    15                     int arr[3] = {temp,nums[j],nums[k]};
    16                     vector<int> ans(arr,arr+3);
    17                     vec.push_back(ans);
    18                     while(j < (int)nums.size() - 1 && nums[j] == nums[j + 1]) j++;
    19                     while(k > j && nums[k] == nums[k - 1]) k--;
    20                     j++;
    21                     k--;
    22                 }
    23                 else if(temp + nums[j] + nums[k] > 0) k--;
    24                 else j++;
    25             }
    26         }
    27         return vec;
    28     }
    29 };
  • 相关阅读:
    兰迪·波许教授的最后一课
    How can I convert from GdiPlus::Image to CBitmap?
    环境变量以及ControlSet
    判断操作系统类型的多种方法
    顺序表
    操作系统版本号
    64bit操作系统的重定向
    CListCtrl资料
    Custom draw 和 Owner draw 的区别
    Silent Install / Uninstall
  • 原文地址:https://www.cnblogs.com/tracy520/p/8329072.html
Copyright © 2020-2023  润新知