首页 > 笔经面经 > 分享携程笔试两道编程,AC(java版)

分享携程笔试两道编程,AC(java版)

头像
java渣洼
发布于 2016-09-17 21:51:35 APP内打开
赞 1 | 收藏 27 | 回复5 | 浏览8358
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);
		}
	}
} 


5条回帖

回帖
加载中...
话题 回帖

笔经面经近期热帖

历年真题 真题热练榜 24小时
技术(软件)/信息技术类
查看全部

近期精华帖

热门推荐