在 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 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告