在 C++ 中計算陣列中兩個給定元素之間的元素個數


給定一個包含整數元素的陣列和兩個數字 start 和 end,任務是計算陣列中 start 和 end 之間存在的元素個數。

陣列是一種資料結構,可以儲存固定大小的相同型別元素的順序集合。陣列用於儲存資料集合,但通常將陣列視為相同型別的變數集合更有用。如果起始元素出現多次,我們將考慮起始元素的第一次出現;如果結束元素出現多次,我們將考慮結束元素的最後一次出現。

例如

Input − int arr[] = {1, 2, 3, 4, 5, 6, 7}
      Start = 1 and End = 7
Output − count is 5

說明 - 在給定的陣列中,有 7 個元素,範圍是 1-7。因此,在這個範圍之間,共有 5 個元素。

Input − int arr[] = {1, 2, 3, 4, 5, 6, 7}
      Start = 7 and End = 9
Output − count is 0

說明 - 在給定的陣列中,有 7 個元素,範圍是 7-9。因此,在這個範圍之間,沒有元素,所以計數為 0。

下面程式中使用的方案如下

  • 輸入一個數組,例如,int arr[]

  • 使用 length() 函式計算兩個陣列的長度,該函式將根據陣列中的元素返回一個整數值。

  • 從 i 為 0 開始迴圈,直到 i 小於陣列的大小

  • 在迴圈內,檢查 arr[i] 是否等於 start,如果是,則中斷迴圈

  • 檢查 i 是否大於 size-1,如果是,則返回

  • 使用另一個迴圈,從 j 為 size-1 開始,直到 j 大於等於 i+1,並遞減 j

  • 檢查 arr[j] 是否等於 end,如果是,則中斷迴圈

  • 檢查 j 是否等於 1,如果是,則返回 0

  • 返回 j-i-1

  • 列印結果。

示例

 即時演示

#include <iostream>
using namespace std;
// For counting the numbers between the two elements
int countelements(int ar[], int n, int start, int end){
   // Find start
   int i = 0;
   for (i = 0; i < n; i++){
      if (ar[i] == start){
         break;
      }
   }
   // If start is not present or present at the last
   if (i >= n-1){
      return 0;
   }
   // Find end
   int j;
   for (j = n-1; j >= i+1; j--){
      if (ar[j] == end){
         break;
      }
   }
   // If end is not present
   if (j == i){
      return 0;
   }
   // number of elements between the two elements
   return (j - i - 1);
}
// Main Function
int main(){
   int ar[] = { 1, 6, 2, 5, 9, 8, 3, 7, 4 };
   int n = sizeof(ar) / sizeof(ar[0]);
   int start = 5, end = 4;
   cout <<"count is " <<countelements(ar, n, start, end);
   return 0;
}

輸出

如果我們執行以上程式碼,我們將得到以下輸出:

count is 4

更新於: 2020年5月15日

1K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.