Java求调

P2249 【深基13.例1】查找

qishuang35 @ 2024-10-09 11:40:08

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();

        int num[] = new int[n];
        for (int i = 0; i < n; i++) {
            num[i] = scanner.nextInt();
        }
        int target[] = new int[m];
        for (int i = 0; i < m; i++) {
            target[i] = scanner.nextInt();
        }
        for (int i = 0; i < m; i++) {
            System.out.print(s(target[i], num) + " ");
        }
    }

    private static int s(int target, int[] num) {
        int left = 0, right = num.length - 1;
        int result = -1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (target < num[mid]) {
                right = mid - 1;
            } else if (target > num[mid]) {
                left = mid + 1;
            } else {
                result = mid + 1;
                right = mid - 1;
            }
        }

        return result;
    }
}

|