Skip to content

Commit 409d00b

Browse files
Improvement
Signed-off-by: Leo Ma <begeekmyfriend@gmail.com>
1 parent 7fa2b54 commit 409d00b

File tree

2 files changed

+25
-15
lines changed

2 files changed

+25
-15
lines changed

084_largest_rectangle_in_histogram/rect_in_histogram.c

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,34 @@
33

44
static int largestRectangleArea(int* heights, int heightsSize)
55
{
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;
711
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--;
1514
}
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--;
1823
}
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);
2031
max_area = area > max_area ? area : max_area;
2132
}
33+
2234
return max_area;
2335
}
2436

169_majority_element/majority.c

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,8 @@
33

44
static int majorityElement(int* nums, int numsSize)
55
{
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++) {
98
if (count == 0) {
109
major = nums[i];
1110
count++;
@@ -15,7 +14,6 @@ static int majorityElement(int* nums, int numsSize)
1514
count--;
1615
}
1716
}
18-
1917
return major;
2018
}
2119

0 commit comments

Comments
 (0)