博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 4Sum
阅读量:4695 次
发布时间:2019-06-09

本文共 1406 字,大约阅读时间需要 4 分钟。

原题链接在这里:

题目:

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]]

题解:

这道题其实是的扩展,使用的方法基本相同,只是多加了一层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 public class Solution { 2     public List
> fourSum(int[] nums, int target) { 3 List
> res = new ArrayList
>(); 4 if(nums == null || nums.length < 4){ 5 return res; 6 } 7 8 Arrays.sort(nums); 9 for(int i = 0; i
0 && nums[i] == nums[i-1]){11 continue;12 }13 14 for(int j = i+1; j
i+1 && nums[j] == nums[j-1]){16 continue;17 }18 19 int l = j+1;20 int r = nums.length-1;21 while(l
target){26 r--;27 }else{28 List
item = new ArrayList
();29 item.add(nums[i]);30 item.add(nums[j]);31 item.add(nums[l]);32 item.add(nums[r]);33 res.add(item);34 l++;35 r--;36 while(l

类似. 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4825051.html

你可能感兴趣的文章
(Frontend Newbie) Web三要素(一)
查看>>
(转载-学习)python wsgi 简介
查看>>
QPushButton 控制两种状态
查看>>
一点小基础
查看>>
PHP 自动加载类 __autoload() 方法
查看>>
JDK中的Timer和TimerTask详解(zhuan)
查看>>
【python练习】ATM&购物商城程序
查看>>
nginx 日志问题(\x22)
查看>>
装饰器、迭代器、生成器
查看>>
类对象作为类成员
查看>>
面向对象和面向过程的区别及优劣对比详解
查看>>
const与指针
查看>>
thsi指针的一些用法及作用
查看>>
c++友元
查看>>
c++运算符重载
查看>>
一元运算符重载
查看>>
Windows 远程栈溢出挖掘
查看>>
(网页)the server responded with a status of 403 (Forbidden)
查看>>
葡萄城报表介绍:Java 报表
查看>>
android 通知消息一
查看>>