【LeetCode-面試演算法經典-Java實現】【018-4Sum(四個數的和)】,leetcode--java
【018-4Sum(四個數的和)】【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】原題
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:
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)
題目大意
給定一個整數數組,找出a + b + c + d = target的唯一解。
解題思路
先確定a和d的兩個數,對於a和d兩個數,不能同時重複使用。然後再確定b和c,同樣這兩個數也不能同時重複使用。找出所有滿足條件的解,同時可以保證解不重複。
代碼實現
import java.util.ArrayList;import java.util.Arrays;import java.util.LinkedList;import java.util.List;public class Solution { public List<List<Integer>> fourSum(int[] num, int target) { List<List<Integer>> result = new LinkedList<>(); if (num == null || 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<Integer> four = new ArrayList<>(4); 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://blog.csdn.net/derrantcm/article/details/46997233】
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。