分享携程笔试两道编程,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工程师#
全部评论
二分查找直接用Arrays.BinarySearch(arr,num)然后输出就行了
点赞 回复 分享
发布于 2016-09-17 22:27
二分查找,本身输入测试用例就是O(n)了,所以二分查找并没有意义,所以我是一边输入一边比对目标数的,一样AC 股票 import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { String tmp[] = in.nextLine().split(","); int buy = Integer.parseInt(tmp[0]), max = 0; for (int i = 1; i < tmp.length; i++) { int now = Integer.parseInt(tmp[i]); if (now < buy) { buy = Integer.parseInt(tmp[i]); } else { max = Math.max(max, now - buy); } } System.out.println(max); } in.close(); } }
点赞 回复 分享
发布于 2016-09-17 21:55
话说鞋城我都没找到投递的入口,求传送门。
点赞 回复 分享
发布于 2016-09-17 22:36
面试开始了吗
点赞 回复 分享
发布于 2016-09-19 10:18
面试开始了吗?我也是这样的,可是选择题很糟糕
点赞 回复 分享
发布于 2016-09-20 17:10

相关推荐

点赞 28 评论
分享
牛客网
牛客企业服务