C++程式:查詢陣列中左右兩側奇偶數數量相同的索引?


查詢左右兩側奇偶數數量相同的陣列索引,是指在陣列中找到一個元素,其左右兩側的奇數或偶數數量相等,即左側的數字數量 = 右側的數字數量。

這裡,我們需要一些與概念相關的定義:

陣列 - 一個儲存相同資料型別元素的容器。

陣列索引 - 元素的位置稱為其索引。陣列的索引始終從 0 開始。

偶數 - 能被 2 整除的數。

奇數 - 不能被 2 整除的數。

一個整數可以是偶數或奇數。

現在,讓我們看一個例子,使概念更清晰。

Input: arr[] = {4, 3, 2, 1, 2}
Output : 2

解釋

在索引 2 處,其左側有一個奇數,右側有一個奇數。

我們有一個包含 n 個整數的陣列,需要找到陣列元素的索引,使得其左側有偶數個元素,右側也有偶數個元素,或者需要找到其左側奇數元素的頻率等於其右側奇數元素的頻率。如果沒有這樣的條件,則需要輸出 -1;如果有這樣的條件,則需要輸出其索引。

演算法

要計算左右兩側奇偶數數量相同的元素的索引,我們需要找到給定元素左側和右側的元素數量。

給定陣列 arr[],陣列元素數量為 n。

Step 1 : For i -> 0 to n, follow step 2 - 5:
Step 2: initialise e_l, o_l, e_r, o_r to 0.
Step 3: for j -> o to i
   Step 3.1 : count values for e_l and o_l.
Step 4: for j -> i+1 to n
   Step 4.1 : count values for e_r and o_r.
Step 5: if(e_l == e_r) or (o_l == e_r ) , print i.

示例

 線上演示

#include <iostream>
using namespace std;
int main() {
   int arr[] = {4, 3, 2, 1, 2};
   int n = 5;
   cout<<"The array is : ";
   for(int i = 0; i < n; i++) {
      cout<<arr[i]<<" ";
   }
   cout<<"\nThe index of the element with the same count of even or odd numbers on both sides = ";
   for (int i = 0; i < n; i++) {
      int o_l = 0, e_l = 0;
      int o_r = 0, e_r = 0;
   for (int j = 0; j < i; j++) {
      if (arr[j] % 2 == 0)
         e_l++;
      else
         o_l++;
   }
   for (int k = n - 1; k > i; k--) {
      if (arr[k] % 2 == 0)
         e_r++;
      else
         o_r++;
   }
   if (e_r == e_l || o_r == o_l)
      cout<<i<<endl;
   }
   return 0;
}

輸出

The array is : 4 3 2 1 2
The index of the element with the same count of even or odd numbers on both sides = 2

更新於: 2019年10月4日

262 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告

© . All rights reserved.