在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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP