分享携程笔试两道编程,AC(java版)
1.二分查找 import java.util.Scanner; public class Ctrip_1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int x = in.nextInt(); int n = in.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i]=in.nextInt(); } int res = -1; int low = 0; int high = arr.length - 1; while (low <= high) { int mid = (low + high) / 2; if (x == arr[mid]) { res =mid; break; } else if (x < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } if(res ==-1){ res = res-low; } System.out.println(res); } } } 输入 5 1 3 6 输出 -3
2.股票利润 import java.util.Scanner; public class Ctrip_2 { public static void main(String[] args) { Scanner in = new Scanner(System.in); while(in.hasNextLine()){ String s = in.nextLine(); String[] str = s.split(","); int [] price = new int[str.length]; for(int i = 0 ; i<price.length;i++){ price[i] = Integer.parseInt(str[i]); } int max= 0; int min=price[0]; for(int i = 1; i<price.length;i++){ if(price[i]>min){ max=price[i]-min>max?price[i]-min:max; }else { min = price[i]; } } System.out.println(max); } } }
#携程##Java工程师#