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

万万没想到之抓捕孔连顺

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型来处理结果。

全部评论

相关推荐

03-27 01:58
已编辑
西北工业大学 Java
在平静中度过当下:如果这个bg也简历挂的话可能他们现在不缺人了吧,我也是这两天投的,阿里和快手投的岗都是简历秒挂
点赞 评论 收藏
分享
牛客51274894...:照片认真的吗,找个专门拍证件照的几十块钱整端正点吧,要不就别加照片
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务