在 C++ 中统计排序矩阵中小于或等于 x 的元素个数


给定一个大小为 n x n 的矩阵,一个整数变量 x,并且矩阵中的元素按排序顺序排列,任务是计算等于或小于 x 的元素个数。

输入 -

matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {6, 7, 8}} and X = 4

输出 -

count is 4

解释 - 我们需要将矩阵数据与值 x 进行匹配,因此小于或等于 x(即 4)的元素为 1、2、3、4。所以计数为 4。

输入 -

matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {6, 7, 8}} and X = 0

输出 -

count is 0

解释 - 我们需要将矩阵数据与值 x 进行匹配,因此没有小于或等于 x 的元素。所以计数为 0。

下面程序中使用的算法如下

  • 输入矩阵的大小,然后创建大小为 nxn 的矩阵

  • 启动循环,I 从 0 到行大小

  • 在循环 I 内部,启动另一个循环 j 从 0 到列大小

  • 现在,检查 matrix[i][j] 是否等于 x,如果是,则将计数增加 1,否则忽略条件

  • 返回总计数

  • 打印结果。

示例

 在线演示

#include <bits/stdc++.h>
using namespace std;
#define size 3
//function to count the total elements
int count(int matrix[size][size], int x){
   int count=0;
   //traversing the matrix row-wise
   for(int i = 0 ;i<size; i++){
      for (int j = 0; j<size ; j++){
         //check if value of matrix is less than or
         //equals to the x
         if(matrix[i][j]<= x){
            count++;
         }
      }
   }
   return count;
}
int main(){
   int matrix[size][size] ={
      {1, 2, 3},
      {4, 5, 6},
      {7, 8, 9}
   };
   int x = 5;
   cout<<"Count of elements smaller than or equal to x in a sorted matrix is: "<<count(matrix,x);
   return 0;
}

输出

如果我们运行以上代码,我们将得到以下输出 -

Count of elements smaller than or equal to x in a sorted matrix is: 5

更新于: 2020-06-06

148 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.