【Leetcode】4Sum

题目链接:https://leetcode.com/problems/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)

思路:

在3sum基础上再嵌套一层循环,时间复杂度为O(n^3),最好的方法是O(n^2*logn),参考网上的解法,此处就不列了

算法:

	List<List<Integer>> lists = new ArrayList<List<Integer>>();

	public List<List<Integer>> fourSum(int[] nums, int target) {
		if (nums.length < 4)
			return lists;
		Arrays.sort(nums);
		for (int i = 0; i < nums.length; i++) {
			threeSum(nums, i + 1, nums[i], target);
		}
		return lists;
	}

	public List<List<Integer>> threeSum(int[] nums, int start, int fnum, int target) {
		for (int i1 = start; i1 < nums.length; i1++) {
			int i2 = i1 + 1;
			int i3 = nums.length - 1;
			while (i2 < i3) {
				if (nums[i2] + nums[i3] + nums[i1] == target - fnum) {
					List<Integer> list = new ArrayList<Integer>();
					list.add(fnum);
					list.add(nums[i1]);
					list.add(nums[i2]);
					list.add(nums[i3]);
					if (!lists.contains(list))
						lists.add(list);
					i2++;
					i3--;
				} else if (nums[i2] + nums[i3] + nums[i1] > target - fnum) {
					i3--;
				} else if (nums[i2] + nums[i3] + nums[i1] < target - fnum) {
					i2++;
				}
			}
		}
		return lists;
	}


你可能感兴趣的:(【Leetcode】4Sum)