• LeetCode 18. 4Sum


    原题链接在这里:https://leetcode.com/problems/4sum/

    题目:

    Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

    Note: The solution set must not contain duplicate quadruplets.

    For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
    A solution set is:
    [
      [-1,  0, 0, 1],
      [-2, -1, 1, 2],
      [-2,  0, 0, 2]
    ]

    题解:

    这道题其实是3Sum的扩展,使用的方法基本相同,只是多加了一层loop.

    但要注意一点:For inner j loop, if statement, 判断overflow 时要写成 j>i+1, 而不是j>0, 与 j 的 初始条件有关。若是写成j>0的话,含有四个相同数的输入就会被跳过. e.g. 0,0,0,0 target = 0.

    Time Complexity: O(n^3), 两层for, 每一层用时n, 内层for里面的while 用了O(n) time, 一共用了O(n^3).

    Space: O(1), regardless res.

    AC Java:

     1 class Solution {
     2     public List<List<Integer>> fourSum(int[] nums, int target) {
     3         List<List<Integer>> res = new ArrayList<List<Integer>>();
     4         if(nums == null || nums.length < 4){
     5             return res;
     6         }
     7         
     8         Arrays.sort(nums);
     9         for(int i = 0; i<nums.length-3; i++){
    10             if(i>0 && nums[i]==nums[i-1]){
    11                 continue;
    12             }
    13             
    14             for(int j = i+1; j<nums.length-2; j++){
    15                 if(j>i+1 && nums[j] == nums[j-1]){
    16                     continue;
    17                 }
    18                 
    19                 int p = j+1;
    20                 int q = nums.length-1;
    21                 while(p<q){
    22                     int sum = nums[i]+nums[j]+nums[p]+nums[q];
    23                     if(sum<target){
    24                         p++;
    25                     }else if(sum>target){
    26                         q--;
    27                     }else{
    28                         res.add(Arrays.asList(nums[i], nums[j], nums[p], nums[q]));
    29                         p++;
    30                         q--;
    31                         
    32                         while(p<q && nums[p]==nums[p-1]){
    33                             p++;
    34                         }
    35                         
    36                         while(p<q && nums[q]==nums[q+1]){
    37                             q--;
    38                         }
    39                     }
    40                 }
    41             }
    42         }
    43         
    44         return res;
    45     }
    46 }

    类似4Sum II

  • 相关阅读:
    angular js 删除及多条删除
    angular js 页面修改数据存入数据库
    angular js 页面添加数据保存数据库
    angular js 分页
    内置函数和匿名函数
    装饰器,迭代器,生成器
    函数的进阶
    函数
    文件操作
    列表,字典
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4825051.html
Copyright © 2020-2023  润新知