Skip to content

Commit 44aa8de

Browse files
added next greater element 1 (bruteforce approach)
1 parent 01cfc89 commit 44aa8de

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
2+
3+
4+
The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.
5+
6+
You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.
7+
8+
For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.
9+
10+
Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.
11+
12+
13+
14+
15+
16+
17+
18+
19+
20+
21+
class Solution {
22+
public:
23+
int linearSearch(vector<int> v1, int k, int start) {
24+
for (int i = start; i < v1.size(); i++) {
25+
if (v1[i] > k) {
26+
return v1[i];
27+
}
28+
}
29+
return -1;
30+
}
31+
32+
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
33+
vector<int> ans;
34+
for (int i = 0; i < nums1.size(); i++) {
35+
int j = 0;
36+
while (j < nums2.size()) {
37+
if (nums1[i] == nums2[j]) {
38+
int result = linearSearch(nums2, nums2[j], j);
39+
if (result != -1) {
40+
ans.push_back(result);
41+
} else {
42+
ans.push_back(-1);
43+
}
44+
break;
45+
}
46+
j++;
47+
}
48+
}
49+
return ans;
50+
}
51+
};

0 commit comments

Comments
 (0)