4 sum

作者: yanyuchen | 来源:发表于2017-06-03 03:40 被阅读0次

解题报告, 这个做的比较绝望, 用了two points, recursion, memorization= =, 思路很简单, 就是边界条件比较难办, 还有去重什么的 , 算是入门级吧

public class Solution {    public List> fourSum(int[] nums, int target) {                List> result = new ArrayList<>();        Arrays.sort(nums);        // start and end boundary        int[][] hash = new int[nums.length][nums.length];              for (int i = 0; i< nums.length; i ++){            for(int j = nums.length -1; j >= 0; j--){                                                                              if(hash[i][j] > 0) break;                hash[i][j] = 1;                hash[j][i] = 1;                                                            if(i+1 < j -1 &&nums[i] == nums[j]){                                                          int tempSum = nums[i]*4;                    if(tempSum == target) {                        result.add(Arrays.asList(nums[i],nums[i], nums[i], nums[i]));                      //  return result;                    }                    i = i + 1;                    j = j -1;                }                              getSum(nums, target, i, j, result);            }        }                        return result;                    }    private void getSum(int[] nums, int t, int start, int end, List> result){                            if(start >= end) return;        int s = start + 1;        int e = end - 1;            // if(s > e) return;                while(s < e){            int sum = nums[s] + nums[e] + nums[start] + nums[end];            if(sum == t){                Listtemp = new ArrayList<>();

temp.add(nums[start]);

temp.add(nums[s]);

temp.add(nums[e]);

temp.add(nums[end]);

while(s + 1 < e && nums[s] == nums[s + 1]) s++;

while(e - 1 > s && nums[e] == nums[e - 1]) e--;

s++;

e--;

if(result.contains(temp)){

continue;

}else{

result.add(temp);

}

}else if(sum < t){

s++;

}else{

e--;

}

}

}

}

相关文章

  • two sum&&three sum&&four sum&&th

    two sum 3 sum 3Sum Closest 4 sum 利用set来实现: 3 sum 4 sum

  • PowerBI DAX CALCULATE/SUM/COUNT/

    SUM CALCULATE(SUM...) COUNT 4.COUNTROWS COUNTBLANK 计算空值的个数

  • 二维数组

    sum()的函数原型:int sum( int (*ar2)[4], int size );//传递一个指向由 4...

  • 写一个sum函数使得以下表达式的值正确

    sum(1,2,3).sumOf();//6sum(2,3)(2).sumOf();//7sum(1,2,3,4)...

  • 4 sum

    4 sum Given an array nums of n integers and an integer ta...

  • 4 sum

    solution 1: sort the array, then fix two,using two pointe...

  • 4 Sum

    题目 Given an array S of n integers, are there elements a, ...

  • 4 sum

    解题报告, 这个做的比较绝望, 用了two points, recursion, memorization= =,...

  • 15+18、3Sum 4Sum

    15、3Sum Example 复杂度 思路 解法 18、4Sum Example 解法

  • Day-13求和函数

    今天学习了SUM SUMIF SUMIFS的用法 1、连续区域求和=SUM(B4:B8)这里输入SUM函数选取求...

网友评论

      本文标题:4 sum

      本文链接:https://www.haomeiwen.com/subject/ssspfxtx.html