File tree 1 file changed +21
-15
lines changed
scripts/algorithms/L/Largest Number At Least Twice of Others
1 file changed +21
-15
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 0 ms (Top 100.0%) | Memory: 40.50 MB (Top 45.54%)
2
+
1
3
class Solution {
2
4
public int dominantIndex (int [] nums ) {
3
- int max = -1 ;
4
- int smax = -1 ;
5
-
6
- for (int i =0 ;i <nums .length ;i ++){
7
-
8
- if (max == -1 || nums [i ] >= nums [max ]){
9
- smax = max ;
10
- max = i ;
11
- }else if (smax == -1 || nums [i ] >= nums [smax ]){
12
- smax = i ;
13
- }
5
+ if (nums == null || nums .length == 0 ){
6
+ return -1 ;
14
7
}
15
8
16
-
17
- if (nums [max ] >= 2 *nums [smax ]){
18
- return max ;
9
+ if (nums .length == 1 ){
10
+ return 0 ;
19
11
}
12
+ int max = Integer .MIN_VALUE + 1 ;
13
+ int secondMax = Integer .MIN_VALUE ;
14
+ int index = 0 ;
20
15
16
+ for (int i = 0 ; i < nums .length ; i ++){
17
+ if (nums [i ] > max ){
18
+ secondMax = max ;
19
+ max = nums [i ];
20
+ index = i ;
21
+ } else if (nums [i ] != max && nums [i ] > secondMax ){
22
+ secondMax = nums [i ];
23
+ }
24
+ }
25
+ if (secondMax * 2 <= max ){
26
+ return index ;
27
+ }
21
28
return -1 ;
22
-
23
29
}
24
30
}
You can’t perform that action at this time.
0 commit comments