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

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

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)
Java代码:

public class Solution {    public List
> fourSum(int[] num, int target) { List
> result = new ArrayList
>(); if (num.length < 4) { return result; } Arrays.sort(num); for (int i = 0; i < num.length - 3; i++) { if (i > 0 && num[i] == num[i - 1]) { continue; } for (int j = num.length - 1; j > i + 2; j--) { if (j < num.length - 1 && num[j] == num[j + 1]) { continue; } int start = i + 1; int end = j - 1; int n = target - num[i] - num[j]; while (start < end) { if (num[start] + num[end] == n) { List
four = new ArrayList
(); four.add(num[i]); four.add(num[start]); four.add(num[end]); four.add(num[j]); result.add(four); do { start++; } while (start < end && num[start] == num[start - 1]); do { end--; } while (start < end && num[end] == num[end + 1]); } else if (num[start] + num[end] < n) { do { start++; } while (start < end && num[start] == num[start - 1]); } else { do { end--; } while (start < end && num[end] == num[end + 1]); } } } } return result; }}
 

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

你可能感兴趣的文章
设置tabbaritem的title的颜色及按钮图片
查看>>
动态设置label的高度
查看>>
获取 一个文件 在沙盒Library/Caches/ 目录下的路径
查看>>
图片压缩
查看>>
检测缓存文件是否超时
查看>>
十进制字符串转十六进制字符串
查看>>
属性字符串(富文本)的使用
查看>>
cell上label的背景颜色在选中状态下改变的解决办法
查看>>
GPS定位
查看>>
地图、显示用户位置、大头针
查看>>
自定义大头针
查看>>
UIButton添加block点击事件
查看>>
利用runtime给类别添加属性
查看>>
本地推送
查看>>
FMDB的使用
查看>>
UIImage存为本地文件与UIImage转换为NSData
查看>>
[转]打印质数的各种算法
查看>>
[转]javascript with延伸的作用域是只读的吗?
查看>>
php的autoload与global
查看>>
IE不支持option的display:none属性
查看>>