• [array] leetCode-15. 3Sum-Medium


    leetCode-15. 3Sum-Medium

    descrition

    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: 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]
    ]
    

    解析

    方法1

    3 重循环,时间复杂度-O(n^3),空间复杂度-O(1)

    for(int i=0; i<array.size(); i++){
    	for(int j=i+1; j<array.size(); j++){
    		for(int k=j+1; k<array.size(); k++){
    			// 检查是否合法
    		}
    	}
    }
    

    方法2

    思考方向:是否可以减少方法 1 中的循环查找次数??

    时间复杂度-O(n^2),空间复杂度-O(1)。

    对数组进行排序,需要时间 O(nlog(n))。使用两重循环,最外层循环 a=array[i],内层循环使用双向指针进行遍历,b 从左到右,c 从右到左,思想和 two sum 一样。(参看代码)

    code

    
    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <unordered_map>
    
    using namespace std;
    
    class Solution{
    public:
    	vector<vector<int> > threeSum(vector<int>& nums){
    		// The solution set must not contain duplicate triplets.
    		vector<vector<int> > ans;
    		sort(nums.begin(), nums.end()); // ascending
    		for(int i=0; i<nums.size(); i++){
    			int target = -nums[i];
    			int ileft = i+1;
    			int iright = nums.size()-1;
    			while(ileft < iright){
    				int sum = nums[ileft]+nums[iright];
    				if( sum == target){
    					// answer
    					vector<int> temp(3);
    					temp[0] = nums[i];
    					temp[1] = nums[ileft];
    					temp[2] = nums[iright];
    					ans.push_back(temp);
    					// skip duplicate
    					while(ileft<iright && nums[ileft] == temp[1])
    						ileft++;
    					while(ileft<iright && nums[iright] == temp[2])
    						iright--;
    				}else if (sum < target){
    					ileft++;
    				}else{
    					// sum > target
    					iright--;
    				}
    			}
    
    			// skip duplicate
    			while((i+1)<nums.size() && nums[i+1] == nums[i])
    				i++;
    			// i point to the same value, after the i++ in the for loop, i will point to next value
    		}
    
    		return ans;
    	}
    };
    
    int main()
    {
    	return 0;
    }
    
    
  • 相关阅读:
    【Java123】javapoet代码生成代码工具
    【Python123】OptionParser初使用
    【Spring123】JdbcTemplate初使用 以及 ORA-01858: a non-numeric character was found where a numeric was expected, ORA-00911: invalid character解决
    【Java123】解决javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
    git常用命令
    在虚拟机上搭建自己的 git 服务器并创建 git 仓库
    git用法
    Golang gRPC框架3-自签证书验证
    go _nsq
    mysql的备份和恢复
  • 原文地址:https://www.cnblogs.com/fanling999/p/7828880.html
Copyright © 2020-2023  润新知