P2249 【深基13

P2249 【深基13.例1】查找

传送门

注意点:

  1. Java没有算法库,需要手写二分。
  2. 输入输出次数过多,不能用Scanner类来读取,读取的太慢了会导致超时并且内存超限,应该要用快读快输,不过这道题不要快输也行,所以必须记住快读数字,快读字符串,和快输的模板。
  3. 注意防止数组下标越界
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;

public class Main {
	static int n, m, x;
	static int[] nums;

	public static void main(String[] args) throws Exception {
		Read sc = new Read();
		n = sc.nextInt();
		m = sc.nextInt();
		nums = new int[1000002];
		for (int i = 1; i <= n; i++) {
			nums[i] = sc.nextInt();
		}
		for (int i = 0; i < m; i++) {
			x = sc.nextInt();
			f(x);
			System.out.print(f(x));
			if (i != m - 1)
				System.out.print(" ");
		}
	}

	public static int f(int x) {
		int l = 1, r =n+1;//不为r = nums.length + 1  这样会导致r = nums.length + 1
		while (l < r) {
			int m = l + (r - l) / 2;
			if (nums[m] >= x)
				r = m;
			else
				l = m + 1;
		}
		return nums[l] == x ? l : -1;
	}

}

//快读
class Read {
	StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

	public int nextInt() throws Exception {
		st.nextToken();
		return (int) st.nval;
	}
}
posted @ 2022-12-26 15:36  QING~h  阅读(98)  评论(0)    收藏  举报