Find index of an element in a Set in C++
Given a set S consisting of N integers and an element K, the task is to find the index of the element K in the set S. If the element is not present in S, print -1.
Examples:
Input: N = 5, S = {1, 2, 3, 4, 6} K = 6
Output: 5
Explanation: 6 is the 5th element in S.
Input: N = 5, S = {1, 2, 3, 4, 6}, K = 5
Output: -1
Explanation: 5 is not present in this set so we give output as -1.
Approach: Follow the steps below to solve the problem:
- Initialize a variable, say index as 1, to store the index of the required element.
- Traverse the set S and perform the following operations:
- If the current element is K, print Index and break out of the loop.
- Otherwise, increment Index.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int GetIndex(set< int > S, int K)
{
int Index = 1;
for ( auto u : S) {
if (u == K)
return Index;
Index++;
}
return -1;
}
int main()
{
set< int > S;
S.insert(1);
S.insert(6);
S.insert(2);
S.insert(3);
S.insert(4);
int K = 6;
cout << GetIndex(S, K) << endl;
return 0;
}
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
01 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...