在 C++ 中查詢位置元素的數量


在本問題中,我們給出二維陣列 mat[n][m]。我們的任務是找出位置元素的數量。

如果元素是行或列的最大或最小元素,則稱該元素為位置元素。

我們舉個例子來理解這個問題,

輸入

mat[][] = {2, 5, 7}
{1, 3, 4}
{5, 1, 3}

輸出

8

說明

元素 2、5、7、1、4、5、1、3 是位置元素。

解決方案方法

問題的簡單解決方案是儲存每一行和每一列的最大和最小元素。然後檢查條件並計數。

程式說明我們解決方案的工作原理:

示例

 即時演示

#include <iostream>
using namespace std;
const int MAX = 100;
int countAllPositionalElements(int mat[][MAX], int m, int n){
   int rowmax[m], rowmin[m];
   int colmax[n], colmin[n];
   for (int i = 0; i < m; i++) {
      int rminn = 10000;
      int rmaxx = -10000;
      for (int j = 0; j < n; j++) {
         if (mat[i][j] > rmaxx)
            rmaxx = mat[i][j];
         if (mat[i][j] < rminn)
            rminn = mat[i][j];
      }
      rowmax[i] = rmaxx;
      rowmin[i] = rminn;
   }
   for (int j = 0; j < n; j++) {
      int cminn = 10000;
      int cmaxx = -10000;
      for (int i = 0; i < m; i++) {
         if (mat[i][j] > cmaxx)
            cmaxx = mat[i][j];
         if (mat[i][j] < cminn)
            cminn = mat[i][j];
      }
      colmax[j] = cmaxx;
      colmin[j] = cminn;
   }
   int positionalCount = 0;
   for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
         if ((mat[i][j] == rowmax[i]) || (mat[i][j] ==
            rowmin[i]) || (mat[i][j] == colmax[j]) || (mat[i][j] == colmin[j])){
            positionalCount++;
         }
      }
   }
   return positionalCount;
}
int main(){
   int mat[][MAX] = {
      { 2, 5, 7 },
      { 1, 3, 4 },
      { 5, 1, 3 }
   };
   int m = 3, n = 3;
   cout<<"Number of positional elements is "<<countAllPositionalElements(mat, m, n);
   return 0;
}

輸出

Number of positional elements is 8

更新於:15-Mar-2021

135 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告