LeetCode开心刷题第八天——15 3sum 16 3sum cloest

TIME COMPLEXITY:

https://www.bilibili.com/read/cv1334416/

this website is effective because it gives many useful examples and clear calculation process.


This is the first thing I need to clarify at the beginning.

Now I need to clarify two ideas;

First O(logN),In the past I default this value is two.But in fact the complexity include log only means use the divide and conquer 

thoughts,we didn't need to calculate all numbers.So it's not a 'n'.but 'logn'.

Another is an example give us the effective way to calculate complexity

 

15 3sum

Qustion Description:

 

15. 3Sum
Medium
3902439FavoriteShare

 

Given an array nums of n integers, are there elements abc in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

 

 

this question is a complex problem to me because it's hard to detailed classification.

Special Usage:

vector<vector<int>> this container is equivalent to a two-dimensional array.if we use vector<int>,we can only put one variable in this container.But if we overlap the two containers.It can store the contents of an array.But the direct assignment appears to be supported only in C11.So in C98 we have to change into first assign the values to a vector(just like a unary array).

Ideas of solving problems:

First of all,it's important to sort them,because we can see some repetition(重复)in this problem.So if we sort ahead of time,when we go through(遍历)we can skip the same element value as before,so that we can avoid repetition.

Secondly,we need to fix one number ,and then to find the other two.because we have already sorted it.So the number is ranking from small to large,we first start from 0 ,this is the smallest number,and then we find left and right this two number,and verify if we add them together can we get 0 as a result. Another thing to be careful of is when we facing true value,i is larger than 0,then the loop will be ended ,because i ==positive number ,r & l all larger than i,there won't be suitable answer to this problem~

PS:if we use vector,please remeber to clear it before or after you use it.Vector,I have to say,is a really nice tool compares to array.Because it doesn't limit number,in the opposite,if you don't clear it.Each time's result will be linked together.This is not what we want to see.

Complex Analyse:

Time Complex:O(nlogn+n^2) sort algorithm add for(while)

Space Complex:O(1) Space Complexity O,which means the space required is constant and n independent.I think maybe because Space consume doesn't increase with the number of cycles.So space complexity is indepent to n.It's just O(1).

Code Time:

 

#include<iostream>
#include<string>
#include<stdio.h>
#include<string.h>
#include<iomanip>
#include<vector>
#include<list>
#include<queue>
#include<algorithm>
#include<map>
using namespace std;

class Solution {
public:
  vector<vector<int> > threeSum(vector<int>& nums) {
    vector<vector<int> > ans;
    vector<int> temp;
    std::sort(nums.begin(), nums.end());
    const int n = nums.size();
    for (int i = 0; i < n - 2; ++i) {
      if (nums[i] > 0) break;
      if (i > 0 && nums[i] == nums[i - 1]) continue;
      int l = i + 1;
      int r = n - 1;
      while (l < r) {
        if (nums[i] + nums[l] + nums[r] == 0)
        {
          temp.clear();
          temp.push_back(nums[i]);
          temp.push_back(nums[l++]);
          temp.push_back(nums[r--]);
          ans.push_back(temp);
          while (l < r && nums[l] == nums[l - 1]) ++l;
          while (l < r && nums[r] == nums[r + 1]) --r;
        }
        else if (nums[i] + nums[l] + nums[r] < 0) {
          ++l;
        } else {
          --r;
        }
      }
    }
    return ans;
  }
};

int main()
{

    Solution s;
    vector<int> nums,temp_int;
    vector<vector<int> > res;
    int temp;
    char ch1;
    while((ch1=cin.get())!='\n' )
    {
        cin.putback(ch1);
        cin>>temp;
        nums.push_back(temp);
    }
    res=s.threeSum(nums);
    for(vector<vector<int> >::iterator iter2=res.begin();iter2!=res.end();++iter2)
    {
        temp_int=*iter2;
        for(vector<int>::iterator iter=temp_int.begin();iter!=temp_int.end();++iter)
        {
            cout<<*iter;
        }
        cout<<endl;
    }
    //cout<<res<<endl;
    return 0;
}

 16 3sum closest

Problem Description:

 
Medium
114584FavoriteShare

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

The most important thing is to examing the topic.In this topic ,I thought we should calculate the
distance between the target and the approximate value.But actually it only need to output the
approximate value.
When I first handle this problem,I have no idea.But from the similarity between the name of these
two problems we can found that it must have some similarity in code.
First of all.It also need sort.
and then from 0 to n-2(n is the number of vector),firstly I want to sort them and find where is
the critical point(临界点),which means nums(nums is the vector's name) nums[i]>target&&nums[i+1]<target
but in fact it's useless.Because we want to find three numbers' sum is nearest to target.We find
the single nearest number to the target is meaningless.This is because not understanding the problem
clearly,also the answer need to out the three numbers' sum,instead of the absolute value between target
and approximate value.
So carefully analyze the problem is the most important thing in coding.First,what exactly are the
inputs and outputs.what's meaning
The solution idea is from 0 to n-2 traverse(遍历) find all past numbers to combine and use a flag to
record the nearest one,finally output.The same structure with LeetCode15.
TIME COMPLEXITY:O(N^2) I think this is similar to 15 but I don't know why their complexity is different
SPACE COMPLEXITY:O(1)
#include<iostream>
#include<string>
#include<stdio.h>
#include<string.h>
#include<iomanip>
#include<vector>
#include<list>
#include<queue>
#include<algorithm>
#include<map>
using namespace std;

class Solution {
public:
  int threeSumClosest(vector<int>& nums, int target) {
    int d=INT_MAX,l,r,temp,res=0;
    std::sort(nums.begin(), nums.end());
    const int n = nums.size();
    for (int i = 0; i < n - 2; ++i)
    {
      l=i+1;
      r=n-1;
      while(l<r)
      {
          temp=nums[i]+nums[l]+nums[r];
          if(temp==target) return target;
          if(d>abs(temp-target))
          {
              d=abs(temp-target);
              res=temp;
          }
          if(temp>target)
            r--;
          else
            l++;
      }
    }
    return res;
  }
};


int main()
{

    Solution s;
    int target;
    int res;
    cin>>target;
    vector<int> nums;
    int temp;
    char ch1;
    while((ch1=cin.get())!='\n' )
    {
        cin.putback(ch1);
        cin>>temp;
        nums.push_back(temp);
    }
    res=s.threeSumClosest(nums,target);
    cout<<res<<endl;
    return 0;
}

 




转载于:https://www.cnblogs.com/Marigolci/p/11068234.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值