zoukankan      html  css  js  c++  java
  • leetcode -- 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:

    • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ? b ? c ? d)
    • 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)

    2013-07-04

    只能通过小数据,使用的方法和3Sum类似,使用4个指针。

     1 public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
     2         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
     3         int len = num.length;
     4         if(len < 4)
     5             return result;
     6         Arrays.sort(num);
     7         for(int i = 0; i < len - 3; i ++){
     8             for(int j = i + 1; j < len - 2; j++){
     9                 int m = j + 1;
    10                 int n = len -1;
    11                 while(m < n){
    12                     int sum = num[m] + num[n];
    13                     if(sum == target - num[i] - num[j]){
    14                         ArrayList<Integer> list = new ArrayList<Integer>();
    15                         list.add(num[i]);
    16                         list.add(num[j]);
    17                         list.add(num[m]);
    18                         list.add(num[n]);
    19                         result.add(list);
    20                         m ++;
    21                         n --;
    22                         while(m < n && num[m - 1] == num[m]) m++;
    23                         while(m < n && num[n] == num[n + 1]) n--;
    24                     } else if(sum < target - num[i] - num[j]){
    25                         m ++;
    26                     } else {
    27                         n --;
    28                     }
    29                     
    30                 }
    31                 while(j < len -3 && num[j] == num[j + 1]) j++;
    32             }
    33             while(i < len - 4 && num[i] == num[i + 1]) i++;
    34         }
    35         return result;
    36     }
  • 相关阅读:
    检查SQL Server 2005的索引密度和碎片信息(转)
    数据库系统异常排查之DMV(转)
    sql server性能分析--执行sql次数和逻辑次数
    sql语句优化
    C#获取文件夹下的所有文件的文件名
    siebel学习笔记-应用/数据访问控制
    FlexPaper实现文档在线浏览(附源码)
    C# Process.WaitForExit()与死锁
    前端网站
    微信小程序
  • 原文地址:https://www.cnblogs.com/feiling/p/3171272.html
Copyright © 2011-2022 走看看