给定一个随机整数数组和一个数字 x。查找并打印数组中总和为 x 的元素的三元组。打印三元组时,首先打印最小的元素。也就是说,如果一个有效的三元组是 (6, 5, 10) 打印“5 6 10”。没有限制必须在第一行打印 5 个三元组。您可以按任何顺序打印三元组,只需注意三元组中元素的顺序。
import java.util.Arrays;
public class TripletSum {
public static void FindTriplet(int[] arr, int x){
/* Your class should be named TripletSum.
* Don't write main().
* Don't read input, it is passed as function argument.
* Print output and don't return it.
* Taking input is handled automatically.
*/
Arrays.sort(arr);
int b=0, c=0;
for(int a=0; a<arr.length; a++){
b=a+1; c=b+1;
if((arr[a]+arr[b]+arr[c])==x){
System.out.print(a+"");
System.out.print(b+"");
System.out.print(c+"");
}
}
}
}