• leetcode 15. 3Sum


    题目描述如下

    Given an array nums of n integers, are there elements a, b, c 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]
    ]

    解题思路

    1. 排序,使用sort
    2. 依次扫描该有序向量,如:某次选的值为nums[I]
    3. 在nums[I] 右侧(只搜右侧实现题目要求的无重复)搜寻两个值 nums[j] 和 nums[k] 使得 nums[j]+nums[k]=-nums[I],则此时题目要求的找到三个值a,b,c 使得a+b+c=0满足
    • 我第一次做这个题,第三步是先取一个值,然后二分查找另一个值,第三步时间复杂度为 O(nlogn),效率不佳
    • 改进:取 int j = i + 1, k = nums.size() - 1,然后逐渐逼近要找的值
      代码如下(来源于评论区大佬):
    class Solution {
    public:
    	vector<vector<int>> threeSum(vector<int>& nums) {
    		vector<vector<int>> ans;
    		if (nums.size() == 0) {
    			return ans;
    		}
    		sort(nums.begin(), nums.end());
    		for (int i = 0; i < nums.size() && nums[i] <= 0; ++i) {
    			if (i > 0 && nums[i] == nums[i - 1]) {
    				continue;
    			}
    			int sum = -nums[i];
    			for (int j = i + 1, k = nums.size() - 1; j < k;) {
    				int tmp = nums[j] + nums[k];
    				if (sum == tmp) {
    					ans.push_back(vector<int>{nums[i], nums[j], nums[k]});
    					while (j < nums.size() - 1 && nums[j] == nums[j + 1]) {
    						++j;
    					}
    					while (k > 0 && nums[k] == nums[k - 1]) {
    						--k;
    					}
    					++j;
    					--k;
    				}
    				else if (tmp < sum) {
    					++j;
    				}
    				else {
    					--k;
    				}
    			}
    		}
    		return ans;
    	}
    };
    
  • 相关阅读:
    博客园样式设置
    最坏情况为线性时间的选择算法
    棋盘覆盖
    矩阵乘法的Strassen算法及时间复杂度
    大整数乘法及算法时间复杂度
    全排列问题的递归算法(Perm)
    python的lambda
    python的zip函数
    python操作队列
    mysql基础命令
  • 原文地址:https://www.cnblogs.com/yhjd/p/10652006.html
Copyright © 2020-2023  润新知