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

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

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.

Example:Given array nums = [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]]

难度:medium

题目:

给定一整数数组和一目标整数,是否存在4个数的和为指定整数? 找出所有这样不同的4元组。
注意:
答案一定不能包含重复的四元组。

思路:

数组排序,固定一个数,然后降级为3sum

Runtime: 34 ms, faster than 78.86% of Java online submissions for 4Sum.

Memory Usage: 31.7 MB, less than 13.82% of Java online submissions for 4Sum.

class Solution {    public List
> fourSum(int[] nums, int target) { List
> result = new ArrayList(); Arrays.sort(nums); int numsLen = nums.length; for (int k = 0; k < numsLen; k++) { if (0 == k || nums[k - 1] != nums[k]) { for (int i = k + 1; i < numsLen; i++) { if ((k + 1) == i || nums[i - 1] != nums[i]) { for (int left = i + 1, right = numsLen - 1; left < right; left++, right--) { int sum = nums[left] + nums[right] + nums[i] + nums[k]; if (target == sum && ((i + 1) == left || nums[left - 1] != nums[left]) && ((numsLen - 1) == right || nums[right] != nums[right + 1]) ) { result.add(Arrays.asList(nums[k], nums[i], nums[left], nums[right])); } else if (sum > target) { left--; } else { right++; } } } } } } return result; }}

转载地址:http://rvhal.baihongyu.com/

你可能感兴趣的文章
使用阿里云容器服务Jenkins 2.0实现持续集成之Pipeline篇(updated on 2016.12.23)
查看>>
Redis---持久化 ( RDB AOF )
查看>>
Introducing mcrouter: A memcached protocol router for scaling memcached deployments
查看>>
码栈开发手册(四)---编码方式开发(其他功能函数)
查看>>
android动画之interpolator和typeEvaluator用法详解
查看>>
排序算法之Bogo排序
查看>>
Speed up your Internet browsing on Linux with a DNS Cache server
查看>>
我的失败与伟大 —— 合作伙伴的甄别
查看>>
APP运营中必须关注的7大数据指标
查看>>
kettle数据同步的五种方案
查看>>
如何用IE的开发人员工具选择Iframe里面的元素
查看>>
linux 常用命令(1) grep
查看>>
第三方开发的网贷系统安全如何保障
查看>>
Java千百问_05面向对象(006)_is-a,has-a,like-a是什么
查看>>
Android SDK r20.x更新时,没有Android API的问题
查看>>
PHPWind发布新产品架构图
查看>>
GitHub学习笔记
查看>>
Javascript 学习 笔记六
查看>>
RecyclerView+Cardview学习探索
查看>>
【Android】Android自定义带board的圆角控件
查看>>