Leetcode刷题记——18. 4Sum(4个数字和)
来源:互联网 发布:java webservice传xml 编辑:程序博客网 时间:2024/05/29 09:16
一、题目叙述:
Given an array S of n integers, are there elements a, b, c, 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]]
Subscribe to see which companies asked this question
二、解题思路:
搞不懂,我用了和15题一模一样的算法,就把15题3Sum的算法加了个循环和防止重复的判断,就过了。。。。。。
(1)主体思路:循环前三个数,然后二分查找(所以数组要先排序)为target减去前三数和的第四个数,这样复杂度能从O(n4)减到O(n3logn)。
完全照搬15题。。。
三、源码:
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Solution { List<List<Integer>> ans = new ArrayList<List<Integer>>(); public List<List<Integer>> fourSum(int[] nums, int target) { Arrays.sort(nums); int q; int h; //int count = 0; //List<List<Integer>> reslist = new ArrayList<List<Integer>>(); for (int i = 0; i < nums.length; i ++) { if (i > 0 && nums[i] == nums[i-1]) continue;//去除重复 for (int j = i + 1; j < nums.length; j++) { if (j > i+1 && nums[j] == nums[j-1]) continue;//去除重复 for (int k = j + 1; k < nums.length; k++) { if (k > j+1 && nums[k] == nums[k-1]) continue; q = BinarySearch(target-nums[i]-nums[j]-nums[k], nums, k+1, nums.length - 1); if (q > k) { //count ++; List<Integer> list = new ArrayList<Integer>(); list.add(nums[i]); list.add(nums[j]); list.add(nums[k]); list.add(nums[q]); ans.add(list); } } } } return ans; } public int BinarySearch (int k,int[] num,int first, int last) { //int first = 0; //int last = num.length - 1; int mid; while (first <= last) { mid = (first + last) / 2; if (num[mid] > k) last =mid - 1; else if (num[mid] < k) first = mid + 1; else return mid; } return -1; } public static void main(String args[]) { int[] a = {1, 0, -1, 0, -2, 2}; Solution so = new Solution(); System.out.println(so.fourSum(a, 0)); } }
0 0
- Leetcode刷题记——18. 4Sum(4个数字和)
- Leetcode刷题记——15. 3Sum(3个数字和)
- Leetcode刷题记——16. 3Sum Closest(最接近的三个数的和)
- leetcode题记——Two Sum
- Leetcode刷题记——9. Palindrome Number(回文数字)
- 【LeetCode刷题记录】Two Sum
- leetcode刷题记录1:two sum
- leetcode刷题记录--Two Sum
- Leetcode刷题记——136. Single Number(单独的数字)
- leetCode 18.4Sum (4数字和) 解题思路和方法
- LeetCode刷题记录7-从数组中找出指定条件的3个数字
- leetcode刷题记录4--依然数组
- Leetcode刷题记——1.TwoSum
- 4Sum 4个数字的和为目标数
- Leetcode刷题记——41. First Missing Positive(第一个丢失的正数)
- leetcode解题之 18. 4Sum Java版(结果是目标值的四个数字和)
- Leetcode刷题记——17. Letter Combinations of a Phone Number(电话号码的数字组合)
- LeetCode 456. 132 Pattern——LeetCode刷题记录
- webView网页中JS调原生OC方法与JS注入
- Nginx介绍及Nginx的优点
- POJ 2676 Sudoku
- python代码很长,怎样阅读和调试
- Python实现冒泡排序算法
- Leetcode刷题记——18. 4Sum(4个数字和)
- SURF算法matlab实现
- 走迷宫游戏
- IO流基本框架
- caffe fine-tune策略
- 机器视觉开源代码集合(转载)
- iOS 键盘中使用[UIApplication sharedApplication].statusBarFrame
- 微信小程序开发教程(基础篇)8-数据绑定下
- 在Eclipse中安装SVN客户端插件并提交到SVN服务器上