贝克找房笔试(Java实现)

<一>、计算绝对值:

1.题目描述:

给出n个正整数,要求找出相邻两个数字中差的绝对值最小的一对数字,如果有差的绝对值相同的,则输出最前面的一对数。

2<n<=100,正整数都在10^16范围内

输入:

  输入包含1行,第一行为n,第二行是n个用空格分隔的正整数。

输出:

  输出包含一行两个正整数,要求按照原来的顺序输出。

样例输入:

  9

  1 3 4 7 2 6 5 12 32

样例输出:

  3 4

代码1如下:这是自己在编译器实现的,但是进入考试是不行的。

package com.ymm.core;

import java.util.Scanner;

public class Main1 {

	public static void main(String[] args) {
		
		@SuppressWarnings("resource")
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		
		int[] arr = new int[n];
		for(int i = 0;i < n;i++) {
			arr[i] = in.nextInt();
		}

		int min = arr[1] - arr[0];
		int index = 1;
		
		for(int i = 1; i < n;i++) {
			int  tmp = Math.abs(arr[i] - arr[i - 1]);
			if(tmp < min) {
				min = tmp;
				index = i;
			}
		}
		System.out.println(arr[index - 1] + " " + arr[index]);
		
	}

}

 正确代码:

package com.ymm.core;

import java.util.Scanner;

public class Main1 {

	public static void main(String[] args) {
		
		@SuppressWarnings("resource")
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		
		long[] arr = new long[n];
		for(int i = 0;i < n;i++) {
			arr[i] = in.nextInt();
		}

		long min = arr[1] - arr[0];
		int index = 1;
		
		for(int i = 1; i < n;i++) {
			long  tmp = Math.abs(arr[i] - arr[i - 1]);
			if(tmp < min) {
				min = tmp;
				index = i;
			}
		}
		System.out.println(arr[index - 1] + " " + arr[index]);
		
	}

 注意:2<n<=100,正整数都在10^16范围内。

<二>月光宝盒的密码

1.题目描述:

  小希偶然得到了传说中的月光宝盒,然而打开月光宝盒需要一串密码。虽然小希并不知道密码具体是什么,但是月光宝盒的说明书上有一个长度为n(2 <= N <= 50000)的序列a(-10^9 <= a[i] <= 10^9)的范围内。下面写着一段话:密码是这个序列的最长严格上升子序列的长度(严格上升子序列是指,子序列的元素是严格递增的,例如;[5,1,6,2,4]的最长严格上升子序列为[1,2,4]),请你帮小希找到这个密码。

输入:

  第一行:1个数N,N的序列的长度(2 <= N <= 50000)

  第2到N + 1行;每行1个数,对应序列的元素(-10^9 <= a[i] <= 10^9)

输出;

  一个正整数表示严格最长上升子序列的长度。

样例输入:

8

5

1

6

8

2

4

5

10

样例输出:

5

代码如下:

package com.ymm.core;

import java.util.Arrays;
import java.util.Scanner;

public class Main2 {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		
		int n = in.nextInt();
		if(n == 0) {
			System.out.println(0);
			return;
		}
		int[] arr = new int[n];
		for(int i = 0;i < n;i++) {
			arr[i] = in.nextInt();
		}
		
		int[] temp = new int[n];
		int len = 0;
		for(int count : arr) {
			int i = Arrays.binarySearch(temp, 0, len, count);
			if( i < 0) {
				i = -(i + 1);
			}
			temp[i] = count;
			if(i == len) {
				len++;
			}
		}
		System.out.println(len);
	}

}

猜你喜欢

转载自www.cnblogs.com/youdiaodaxue16/p/11333708.html
今日推荐