對應每一個測試案例,輸出兩個數,小的先輸出。若是找不到,則輸出「-1 -1」 java
知識點:
已知數組求兩數的和爲固定值,利用先後兩個指針向中間移動,同時判斷是否知足所求的值(find2()),能夠縮短運行時間(find()) 數組
此題,由於是遞增數組,因此第一次求出a[low]+a[high]==k,則是乘積最小的那個。 測試
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; public class Main { public static void find(int[] a,int target){ int m = 0; int n = 0; boolean flag = false; for(int i = 0; i < a.length; i++){ for(int j = i+1; j < a.length; j++){ if(a[i] * 2 > target){ i = a.length; j = a.length; break; } int temp = a[i] + a[j]; if(temp > target){ break; }else if(temp == target){ m = a[i]; n = a[j]; flag = true; i = a.length; j = a.length; break; } } } if(!flag){ System.out.println("-1 -1"); }else{ if(m > n) System.out.println(n+" "+m); else System.out.println(m+" "+n); } } public static void find2(int[] a, int target){ int low = 0; int high = a.length -1; while(low < high){ if(a[low] + a[high] == target)break; else if(a[low] + a[high] < target) low++; else high--; } if(low < high) System.out.println(a[low]+" "+a[high]); else System.out.println("-1 -1"); } public static void main(String[] args) throws IOException { StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); while(st.nextToken() != st.TT_EOF){ int n = (int) st.nval; st.nextToken(); int target = (int) st.nval; int[] a = new int[n]; int count = 0; while(count < n){ st.nextToken(); a[count++] = (int) st.nval; } find2(a, target); } } }