小红浏览论坛

[题目链接](https://www.nowcoder.com/practice/07606940c60e4746a645052d7502efd5)

思路

论坛中每个帖子有点赞数 和反对数 ,小红喜欢阅读满足 的帖子。给定 个帖子和阈值 ,统计她喜欢的帖子数量。

解题方法

这是一道简单的模拟题。逐个遍历每个帖子,判断其点赞数与反对数的差的绝对值是否不小于 ,满足条件则计数器加一。

样例演示

输入 ,三个帖子分别为

  • 帖子 ,满足条件。
  • 帖子 ,不满足条件。
  • 帖子 ,满足条件。

共有 个帖子满足条件,输出

复杂度分析

  • 时间复杂度:,遍历所有帖子一次。
  • 空间复杂度:,只用常数额外空间。

代码

#include <bits/stdc++.h>
using namespace std;
int main(){
    int n, x, a, b, cnt = 0;
    scanf("%d%d", &n, &x);
    for(int i = 0; i < n; i++){
        scanf("%d%d", &a, &b);
        if(abs(a - b) >= x) cnt++;
    }
    printf("%d\n", cnt);
    return 0;
}
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(), x = sc.nextInt();
        int cnt = 0;
        for (int i = 0; i < n; i++) {
            int a = sc.nextInt(), b = sc.nextInt();
            if (Math.abs(a - b) >= x) cnt++;
        }
        System.out.println(cnt);
    }
}