您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

在C++中,查找未排序数组中元素的起始索引和结束索引

2024/11/23 19:03:14发布197次查看
在这个问题中,我们得到一个包含 n 个未排序整数值的数组 aar[] 和一个整数 val。我们的任务是在未排序的数组中查找元素的开始和结束索引。
对于数组中元素的出现,我们将返回,
“起始索引和结束索引”(如果在数组中找到两次或多次)。
“单个索引”(如果找到)
如果数组中不存在,则“元素不存在”。
让我们举个例子来理解问题,
示例 1input : arr[] = {2, 1, 5, 4, 6, 2, 3}, val = 2output : starting index = 0, ending index = 5
解释
元素 2 出现两次,
第一次出现在索引 = 0 处,
第二次出现在索引处= 5
示例 2input : arr[] = {2, 1, 5, 4, 6, 2, 3}, val = 5output : present only once at index 2
解释
元素 5 在索引 = 2 处仅出现一次,
示例 3input : arr[] = {2, 1, 5, 4, 6, 2, 3}, val = 7output : not present in the array!
解决方法解决该问题的一个简单方法是遍历数组。
我们将遍历数组并保留两个索引值:first 和last。第一个索引将从头开始遍历数组,最后一个索引将从数组尾开始遍历。当第一个和最后一个索引处的元素值相同时结束循环。
算法步骤1 - 循环遍历数组
步骤1.1 - 使用第一个索引从开始遍历,使用最后一个索引进行遍历从末尾开始。
步骤 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 atstart index: 0last index: 8
以上就是在c++中,查找未排序数组中元素的起始索引和结束索引的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product