18 4Sum LeetCode []四の数(中)(JAVA)
トピック住所:https://leetcode.com/problems/4sum/
件名の説明:
アレイのNUMS nは整数および整数ターゲット与え、要素は、+ B + C + D =目標そのNUMS中、B、C、及びDがありますか?ターゲットの合計を与え、アレイ内のすべてのユニークな四つ組を探します。
注意:
ソリューションセットは、重複四つ組を含めることはできません。
例:
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]
]
効果の対象に
四つの要素A、B、Cが存在する場合、整数と目標NUMS対象のN個の配列を指定し、そしてd NUMSは+ B + C + Dが目標の値に等しくなるように決定?クワッドの条件を満たし、繰り返さないすべて特定します。
注意:
答えは、重複したクワッドを含めることはできません。
問題解決のアプローチ
そして3つだけと同じ数が、複数のサイクル15 3Sum LeetCode []と3(中)(JAVA)の数
時間は、直接リターン直接、大きすぎるか小さすぎる最適化された半分の時間を節約され
た場合( + NUMS [nums.length - 1]を事前 <目標||プレ+ NUMS [K + 1]>ターゲット)を続け、
判断の複数の各サイクルの時間を最適化し続けることができます
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
if (nums.length < 4) return res;
Arrays.sort(nums);
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
Integer temp = map.get(nums[i]);
if (temp == null) {
map.put(nums[i], 1);
} else {
map.put(nums[i], temp + 1);
}
}
for (int i = 0; i < nums.length - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < nums.length - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
for (int k = j + 1; k < nums.length - 1; k++) {
if (k > j + 1 && nums[k] == nums[k - 1]) continue;
int pre = nums[i] + nums[j] + nums[k];
if (pre + nums[nums.length - 1] < target || pre + nums[k + 1] > target) continue;
int four = target - pre;
if (four < nums[k]) continue;
Integer count = map.get(four);
if (count == null) continue;
if (nums[k] == four && nums[k] > nums[j]) {
if (count < 2) continue;
}
if (nums[k] == four && nums[k] == nums[j] && nums[j] > nums[i]) {
if (count < 3) continue;
}
if (nums[k] == four && nums[k] == nums[j] && nums[j] == nums[i]) {
if (count < 4) continue;
}
List<Integer> cur = new ArrayList<>();
cur.add(nums[i]);
cur.add(nums[j]);
cur.add(nums[k]);
cur.add(four);
res.add(cur);
}
}
}
return res;
}
}
実行時:25ミリ秒、のJavaに提出するすべてのユーザーの52.37パーセントを打つ
メモリ消費量:41.4メガバイトは、Javaで提出するすべてのユーザーの11.81パーセントを破りました