题解 | #万万没想到之抓捕孔连顺#

万万没想到之抓捕孔连顺

http://www.nowcoder.com/practice/c0803540c94848baac03096745b55b9b

import java.util.*;

public class Main {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        while (sc.hasNext()) {
            int n = sc.nextInt();
            int d = sc.nextInt();
            int[] locations = new int[n];
            for (int i = 0; i < n; i++) {
                locations[i] = sc.nextInt();
            }
            
            long count = dsp(locations, n, d);
            
            System.out.println(count);
        }
    }
    
    public static long dsp(int[] locations, int n, int d) {
        int left = 0, right = 2;
        long count = 0;
        
        int mod = 99997867;
        while (right < n) {
            if (locations[right] - locations[left] > d) 
                left++;
            else if (right - left < 2) 
                right++;
            else {
                long num = right - left;   // 第二位和第三位之间的最远距离
                count += num * (num - 1) / 2L; // 第二位和第三位可以排列组合的数量
                right++;
            }
        }
        
        count %= mod;
        return count;
    }
}

注意要用long型来处理结果。

全部评论

相关推荐

球球别再泡了:坏,我单9要了14
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务