forked from BhaskarJoshi-01/HactoberFest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
how you solved the codin.cpp
59 lines (55 loc) · 1.42 KB
/
how you solved the codin.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Special Array With X Elements Greater Than or Equal X
// Aryan Shinde
//
// Approach:
// In this problem, my approach was to sort the given array first and then apllied binary search,
// which compares the numbers with the iteration count and decreases untill their difference doesnt
// get equal to the ierating element, if found, return that or simply return -1 if not found
// Time complexity: O(nlogn)
// Space complexity: O(1)
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int specialArray(vector<int> &nums)
{
sort(nums.begin(), nums.end());
for (int i = 0; i <= nums.size(); i++)
{
int start = 0;
int end = nums.size() - 1;
while (start <= end)
{
int mid = start + (end - start) / 2;
if (nums[mid] >= i)
{
end = mid - 1;
}
else if (nums[mid] < i)
{
start = mid + 1;
}
}
if (nums.size() - start == i)
{
return i;
}
}
return -1;
}
};
int main()
{
Solution s;
vector<int> nums = {0, 4, 3, 0, 4};
if (s.specialArray(nums) != -1)
cout << s.specialArray(nums) << endl;
else
{
cout << "element not found";
}
return -1;
}