File tree Expand file tree Collapse file tree 2 files changed +25
-15
lines changed
084_largest_rectangle_in_histogram Expand file tree Collapse file tree 2 files changed +25
-15
lines changed Original file line number Diff line number Diff line change 3
3
4
4
static int largestRectangleArea (int * heights , int heightsSize )
5
5
{
6
- int i , max_area = 0 ;
6
+ int * indexes = malloc (heightsSize * sizeof (int ));
7
+ int * left = malloc (heightsSize * sizeof (int ));
8
+ int * right = malloc (heightsSize * sizeof (int ));
9
+
10
+ int i , pos = 0 ;
7
11
for (i = 0 ; i < heightsSize ; i ++ ) {
8
- if (i > 0 && heights [i - 1 ] == heights [i ]) {
9
- continue ;
10
- }
11
- int low = i ;
12
- int high = i ;
13
- while (low - 1 >= 0 && heights [low - 1 ] >= heights [i ]) {
14
- low -- ;
12
+ while (pos > 0 && heights [indexes [pos - 1 ]] >= heights [i ]) {
13
+ pos -- ;
15
14
}
16
- while (high + 1 < heightsSize && heights [high + 1 ] >= heights [i ]) {
17
- high ++ ;
15
+ left [i ] = pos == 0 ? -1 : indexes [pos - 1 ];
16
+ indexes [pos ++ ] = i ;
17
+ }
18
+
19
+ pos = 0 ;
20
+ for (i = heightsSize - 1 ; i >= 0 ; i -- ) {
21
+ while (pos > 0 && heights [indexes [pos - 1 ]] >= heights [i ]) {
22
+ pos -- ;
18
23
}
19
- int area = (high - low + 1 ) * heights [i ];
24
+ right [i ] = pos == 0 ? heightsSize : indexes [pos - 1 ];
25
+ indexes [pos ++ ] = i ;
26
+ }
27
+
28
+ int max_area = 0 ;
29
+ for (i = 0 ; i < heightsSize ; i ++ ) {
30
+ int area = heights [i ] * (right [i ] - left [i ] - 1 );
20
31
max_area = area > max_area ? area : max_area ;
21
32
}
33
+
22
34
return max_area ;
23
35
}
24
36
Original file line number Diff line number Diff line change 3
3
4
4
static int majorityElement (int * nums , int numsSize )
5
5
{
6
- int i , count = 1 ;
7
- int major = nums [0 ];
8
- for (i = 1 ; i < numsSize ; i ++ ) {
6
+ int i , major , count = 0 ;
7
+ for (i = 0 ; i < numsSize ; i ++ ) {
9
8
if (count == 0 ) {
10
9
major = nums [i ];
11
10
count ++ ;
@@ -15,7 +14,6 @@ static int majorityElement(int* nums, int numsSize)
15
14
count -- ;
16
15
}
17
16
}
18
-
19
17
return major ;
20
18
}
21
19
You can’t perform that action at this time.
0 commit comments