利用头尾指针判断
import java.util.Scanner; public class Main { public static void fun(int[] arr,int key,int len){ int pre = 0; int end = len-1; while (pre < end){ if(arr[pre]+arr[end]<key){ pre++; }else if(arr[pre]+arr[end]>key){ end--; }else{ if((pre==0||end==len-1)||(arr[end]!=arr[end+1]&&arr[pre]!=arr[pre-1])){ System.out.println(arr[pre]+" "+arr[end]); pre++; end--; }else if(arr[end]==arr[end+1]){ end--; }else if(arr[pre]==arr[pre]-1){ pre++; } } } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int key = sc.nextInt(); int[] arr = new int[num]; int i=0; while (sc.hasNext()){ arr[i++] = sc.nextInt(); } fun(arr,key,num); } }