给定排序数组arr和整数k,不重复打印arr中所有相加和为k的不降序三元组 例如, arr = [-8, -4, -3, 0, 1, 2, 4, 5, 8, 9], k = 10,打印结果为: -4 5 9 -3 4 9 -3 5 8 0 1 9 0 2 8 1 4 5
思路是固定一个,然后剩下的变成二元组的问题
牛课网有问题,不允许两个值相同?, 如下ac牛客网的代码
import java.util.ArrayList; import java.util.List; import java.util.Scanner; class RsData{ public int a; public int b; public RsData(int a, int b) { this.a = a; this.b = b; } } class RsData3{ public int a; public int b; public int c; public RsData3(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } public class Main { public static Scanner sc = new Scanner(System.in); public static List<RsData> twoAns(int[] arr, int left, int right, int k){ List<RsData> pairList = new ArrayList<>((right - left) / 2); int i = left; int j = right; while(i < j){ int a = arr[i]; int b = arr[j]; if(a + b == k){ pairList.add(new RsData(a, b)); j--; while (i < j && arr[j] == b){ j --; } i++; while (i < j && arr[i+1] == a){ i++; } }else if(a + b < k){ i ++; }else { j --; } } return pairList; } public static List<RsData3> threeAns(int[] arr, int left, int right, int k){ List<RsData3> ans = new ArrayList<>((right - left) / 3); int i = left; while (i <= right - 2){ if(i > left && arr[i] == arr[i-1]){ i++; } int val = arr[i]; int twoLeft = i + 1; int twoRight = right; int twoK = k - val; List<RsData> twoAns = twoAns(arr, twoLeft, twoRight, twoK); if(twoAns != null && ! twoAns.isEmpty()) { for (RsData pair : twoAns) { ans.add(new RsData3(val, pair.a, pair.b)); } } i++; } return ans; } public static void dealTwo(){ int n = sc.nextInt(); int k = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++){ arr[i] = sc.nextInt(); } List<RsData> pairList = twoAns(arr,0,n-1,k); for(RsData rsData: pairList){ Integer a = rsData.a; Integer b = rsData.b; System.out.println(String.format("%d %d", a, b)); } } /* 10 10 -8 -4 -3 0 1 2 4 5 8 9 */ public static void dealThree(){ int n = sc.nextInt(); int k = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++){ arr[i] = sc.nextInt(); } List<RsData3> pairList = threeAns(arr,0,n-1,k); for(RsData3 pair3: pairList){ Integer a = pair3.a; Integer b = pair3.b; Integer c = pair3.c; // 过滤结果适应牛客网,实际应删除如下3行 if(a.equals(b)){ continue; } System.out.println(String.format("%d %d %d", a, b, c)); } } public static void main(String[] args) { dealThree(); } }