[LeetCode] three sums && three cloest sums && four sums

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:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • 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^3)。可以参考两个数求和的办法,对于有序数组,找出两个数的和是N的时间复杂度是O(n)。对数组排序,时间复杂度是O(nLog(n))。最后问题变成先选取一个数,然后再剩下的数组中查询target-nums[i]的两个数,注意查重的办法,那么总的时间复杂度O(n^2)+O(nlog(n))=O(n^2)。
public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        int len=nums.length;
        List<List<Integer>> list=new ArrayList<>();
        for(int i=0;i<len-2;i++)
        {
            //去重
            if(i>0 && nums[i]==nums[i-1]) continue;
            int target2=0-nums[i];
            twoSum(nums, i+1, target2, list);
        }
        return list;
    }
    public void twoSum(int [] nums,int start,int target,List<List<Integer>> list)
    {
        int head=start, end=nums.length-1;
        while(head<end)
        {
            int sum=nums[head]+nums[end];
            if(sum<target)
            {
                head++;
            }
            else if(sum>target)
            {
                end--;
            }
            else
            {
                List<Integer> temp=new ArrayList<>();
                temp.add(nums[start-1]);
                temp.add(nums[head]);
                temp.add(nums[end]);
                list.add(temp);

                //排除可能出现的重复情况,由于是有序数组,从小到大,所以只要一个一个的找重复并跳过即可
                int k=head+1;
                while(k<end && nums[k]==nums[head])k++;
                head=k;

                k=end-1;
                while(k>head && nums[k]==nums[end])k--;
                end=k;
            }
        }
    }
}

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

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int dis=Integer.MAX_VALUE;
        int result=0;
        for(int i=0;i<nums.length-2;i++)
        {
            int target2=target-nums[i];
            int re=twoSumCloest(nums, i+1, target2);
            int d=Math.abs(target-re-nums[i]);
            if(d<dis)
            {
                dis=d;
                result=re+nums[i];
                if(d==0)
                    return target;
            }
        }
        return result;
    }
    public int twoSumCloest(int [] nums,int start,int target)
    {
        int head=start,tail=nums.length-1;
        int re=0,d=Integer.MAX_VALUE;
        while(head<tail)
        {
            int sum=nums[head]+nums[tail];
            if(sum<target)
            {
                int dis=target-sum;
                if(dis<d)
                {
                    d=dis;
                    re=sum;
                }
                head++;
            }
            else if(target<sum)
            {
                int dis=sum-target;
                if(dis<d)
                {
                    d=dis;
                    re=sum;
                }
                tail--;
            }
            else {
                return target;
            }
        }
        return re;
    }
}
时间: 2024-12-12 16:30:00

[LeetCode] three sums && three cloest sums && four sums的相关文章

Leetcode 373. Find K Pairs with Smallest Sums

373. Find K Pairs with Smallest Sums Total Accepted: 1453 Total Submissions: 5789 Difficulty: Medium You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. Define a pair (u,v) which consists of one element from t

【暑假】[实用数据结构]UVa11997 K Smallest Sums

UVa11997 K Smallest Sums  题目: K Smallest Sums You're given k arrays, each array has k integers. There are kk ways to pick exactly one element in each array and calculate the sum of the integers. Your task is to find the k smallest sums among them. In

LeetCode:Range Sum Query - Immutable - 数组指定区间内的元素和

1.题目名称 Range Sum Query(数组指定区间内的元素和) 2.题目地址 https://leetcode.com/problems/range-sum-query-immutable/ 3.题目内容 英文:Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 中文:给定一个数组nums,求出索引i和j之间元素的和,i一定是小于或等于j

Leetcode动态规划【简单题】

目录 Leetcode动态规划[简单题] 53. 最大子序和 题目描述 思路分析 复杂度分析 70.爬楼梯 题目描述 思路分析 复杂度分析 121.买卖股票的最佳时机 题目描述 思路分析 复杂度分析 303.区域和检索-数组不可变 题目描述 思路分析 复杂度分析 Leetcode动态规划[简单题] 动态规划(Dynamic programming,简称DP),是一种把原问题分解为相对简单的子问题的方式求解复杂问题的方法.动态规划相较于递归,拥有更少的计算量. 53. 最大子序和 题目描述 给定一

[LeetCode] Find Pivot Index

Given an array of integers nums, write a method that returns the "pivot" index of this array. We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the ind

[LeetCode] 805. Split Array With Same Average 用相同均值拆分数组

In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.) Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and

LeetCode Find K Pairs with Smallest Sums

原题链接在这里:https://leetcode.com/problems/find-k-pairs-with-smallest-sums/ 题目: You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. Define a pair (u,v) which consists of one element from the first array and one ele

Find K Pairs with Smallest Sums -- LeetCode

You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. Define a pair (u,v) which consists of one element from the first array and one element from the second array. Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) wit

【leetcode】974. Subarray Sums Divisible by K

题目如下: Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K. Example 1: Input: A = [4,5,0,-2,-3,1], K = 5 Output: 7 Explanation: There are 7 subarrays with a sum divisible by K = 5: [4, 5,