在C++中查詢無序陣列中元素的起始和結束索引


在這個問題中,我們得到一個包含n個整數(未排序)的陣列aar[]和一個整數val。我們的任務是*在無序陣列中查詢元素的起始和結束索引*。

對於陣列中元素的出現,我們將返回:

*“起始索引和結束索引”* 如果它在陣列中出現兩次或更多次。

*“單個索引”* 如果它在陣列中只出現一次。

*“元素不存在”* 如果它不存在於陣列中。

讓我們來看一個例子來理解這個問題:

示例1

Input : arr[] = {2, 1, 5, 4, 6, 2, 3}, val = 2
Output : starting index = 0, ending index = 5

解釋

元素2出現了兩次:
第一次在索引 = 0處,
第二次在索引 = 5處。

示例2

Input : arr[] = {2, 1, 5, 4, 6, 2, 3}, val = 5
Output : Present only once at index 2

解釋

元素5只出現一次,在索引 = 2處。

示例3

Input : arr[] = {2, 1, 5, 4, 6, 2, 3}, val = 7
Output : Not present in the array!

解決方案方法

解決這個問題的一個簡單方法是遍歷陣列。

我們將遍歷陣列並保留兩個索引值,first和last。first索引將從陣列開頭遍歷,last索引將從陣列結尾遍歷。當first和last索引處的元素值相同時,結束迴圈。

演算法

  • **步驟1** - 迴圈遍歷陣列

    • **步驟1.1** - 使用first索引從開頭遍歷,last索引從結尾遍歷。

    • **步驟1.2** - 如果任何索引處的數值等於val,則不要增加索引值。

    • **步驟1.3** - 如果兩個索引處的數值相同,則返回。

示例

程式演示了我們解決方案的工作原理

#include <iostream>
using namespace std;

void findStartAndEndIndex(int arr[], int n, int val) {
   int start = 0;
   int end = n -1 ;
   while(1){
   if(arr[start] != val)
      start++;
   if(arr[end] != val)
      end--;
   if(arr[start] == arr[end] && arr[start] == val)
      break;
   if(start == end)
      break;
}
   if (start == end ){
      if(arr[start] == val)
         cout<<"Element is present only once at index : "<<start;
      else
         cout<<"Element Not Present in the array";
   } else {
      cout<<"Element present twice at \n";
      cout<<"Start index: "<<start<<endl;
      cout<<"Last index: "<<end;
   }
}
int main() {
   int arr[] = { 2, 1, 5, 4, 6, 2, 9, 0, 2, 3, 5 };
   int n = sizeof(arr) / sizeof(arr[0]);
   int val = 2;
   findStartAndEndIndex(arr, n, val);
   return 0;
}

輸出

Element present twice at
Start index: 0
Last index: 8

更新於:2022年1月25日

853 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.