-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleaders_in_array.java
More file actions
30 lines (26 loc) · 911 Bytes
/
leaders_in_array.java
File metadata and controls
30 lines (26 loc) · 911 Bytes
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
class Solution {
//Function to find leaders in an array.
public ArrayList<Integer> leaders(int[] nums) {
ArrayList<Integer> ans = new ArrayList<>();
// Iterate through each element in nums
for (int i = 0; i < nums.length; i++) {
boolean leader = true;
/* Check whether nums[i] is greater
than all elements to its right */
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] >= nums[i]) {
/* If any element to the right is greater
or equal, nums[i] is not a leader */
leader = false;
break;
}
}
// If nums[i] is a leader, add it to the ans list
if (leader) {
ans.add(nums[i]);
}
}
// Return the leaders
return ans;
}
}