面試題2:萬萬沒想到之抓捕孔連順

浩瀚藍天dep發表於2020-10-15

要求:

時間限制:C/C++ 1秒,其他語言2秒
空間限制:C/C++ 128M,其他語言256M

題目內容:
給定N(可選作為埋伏點的建築物數)、D(相距最遠的兩名特工間的距離的最大值)以及可選建築的座標,計算在這次行動中,大錘的小隊有多少種埋伏選擇。
注意:
1. 兩個特工不能埋伏在同一地點
2. 三個特工是等價的:即同樣的位置組合(A, B, C) 只算一種埋伏方法,不能因“特工之間互換位置”而重複使用

輸入描述:
第一行包含空格分隔的兩個數字 N和D(1≤N≤1000000; 1≤D≤1000000)
第二行包含N個建築物的的位置,每個位置用一個整數(取值區間為[0, 1000000])表示,從小到大排列(將位元組跳動大街看做一條數軸)

輸出描述:
一個數字,表示不同埋伏方案的數量。結果可能溢位,請對 99997867 取模

輸入例子1:
4 3
1 2 3 4
輸出例子1:
4
例子說明1:
可選方案 (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)

輸入例子2:
5 19
1 10 20 30 50
輸出例子2:
1
例子說明2:
可選方案 (1, 10, 20)

 

程式碼:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        question();
    }

    public static void question() {
        Scanner sc = new Scanner(System.in);
        // 輸入第一行內容
        String firstLine = sc.nextLine();
        // 輸入第二行內容
        String secondLine = sc.nextLine();
        // 按照空格分隔字串
        String[] firstArr = firstLine.split(" ");
        String[] secondArr = secondLine.split(" ");
        // 建築物的數量
        int N = Integer.parseInt(firstArr[0]);
        // 兩名特工間的最大距離
        int D = Integer.parseInt(firstArr[1]);
        // 建築物的位置
        int[] locations = new int[N];
        for (int i = 0; i < secondArr.length; i++) {
            locations[i] = Integer.parseInt(secondArr[i]);
        }
        int left = 0, right = 2;
        // 符合條件的方案個數
        long count = 0L;
        while (right < N) {
            if (locations[right] - locations[left] > D) {
                left++;
            } else if (right - left < 2) {
                right++;
            } else {
                count += calCulateCount(right - left);
                right++;
            }
        }
        count = count % 99997867;
        System.out.println(count);
    }

    /**
     * 計算滿足條件的建築物有幾種選擇方案
     * @param num
     * @return
     */
    public static long calCulateCount(long num) {
        return num * (num - 1) / 2;
    }
}

 

相關文章