zoukankan      html  css  js  c++  java
  • 018 4Sum 四个数的和

    给定一个含有 n 个整数的数组 S,数列 S 中是否存在元素 a,b,c 和 d 使 a + b + c + d = target ?
    请在数组中找出所有满足各元素相加等于特定值的不重复组合。
    注意:解决方案集不能包含重复的四元组合。
    例如,给定数组 S = [1, 0, -1, 0, -2, 2],并且给定 target = 0。
    示例答案为:
    [
      [-1,  0, 0, 1],
      [-2, -1, 1, 2],
      [-2,  0, 0, 2]
    ]
    详见:https://leetcode.com/problems/4sum/description/

    实现语言:Java

    class Solution {
      public List<List<Integer>> fourSum(int[] nums, int target) {
        List result = new ArrayList<List<Integer>>();
        if (nums == null || nums.length < 4){
            return result;
        } 
        
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 3; i++) {
            if (i > 0 && nums[i] == nums[i-1]){
                continue;
            }
            
            for (int j = i + 1; j < nums.length - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j-1]){
                     continue;
                }
                
                int left = j + 1;
                int right = nums.length - 1;
                while (left < right) {
                    int tmp = nums[i] + nums[j] + nums[left] + nums[right];
                    if (tmp == target) {
                        List l = new ArrayList<Integer>();
                        l.add(nums[i]);
                        l.add(nums[j]);
                        l.add(nums[left]);
                        l.add(nums[right]);
                        result.add(l);
                        while (left < right && nums[++left] == nums[left-1]);
                        while (left < right && nums[--right] == nums[right+1]);
                    } else if (tmp > target){
                        while (left < right && nums[--right] == nums[right+1]);
                    } else{
                        while (left < right && nums[++left] == nums[left-1]);
                    } 
                }
            }
        }
        return result;
      }
    }
    

    参考:https://www.jianshu.com/p/1ec86ec8feb6 

  • 相关阅读:
    mysql之SQL入门与提升(一)
    数据库的主键和外键
    mysql项目实战经验
    浅谈设计模式
    记录下sparkStream的做法(scala)
    hive-hbase-handler方式导入hive表数据到hbase表中
    订单风险系统BI
    关于maven 把插件依赖一起打包进jar问题
    一些hbase的shell查询语句
    关于hive表同步类型问题
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8684798.html
Copyright © 2011-2022 走看看