题目描述 给定一个整数数组 tempratures ,表示第 i 天的温度,请你找出下一个大于第 i 天温度的天数距离第 i 天的差值,输出相差的天数;若无大于第 i 天温度的日子,输出0. 输入输出格式 输入格式 第一行有一个整数 tempraturesSize,表示数组 tempratures 的大小; 第二行有 tempraturesSize 个整数,表示数组 tempratures 的所有元素,每个整数用一个空格隔开。 输出格式 输出 tempratures 中每天对应升温的天数。说明提示 -1≤tempraturesSize≤10 5。C语言
时间: 2024-03-16 18:43:32 浏览: 75
以下是一种基于栈的解法:
```c
#include <stdio.h>
#include <stdlib.h>
struct StackNode {
int index;
struct StackNode *next;
};
struct Stack {
struct StackNode *top;
};
void push(struct Stack *stack, int index) {
struct StackNode *node = (struct StackNode *)malloc(sizeof(struct StackNode));
node->index = index;
node->next = stack->top;
stack->top = node;
}
int pop(struct Stack *stack) {
if (stack->top == NULL) {
return -1;
}
struct StackNode *node = stack->top;
stack->top = node->next;
int index = node->index;
free(node);
return index;
}
int peek(struct Stack *stack) {
if (stack->top == NULL) {
return -1;
}
return stack->top->index;
}
int *dailyTemperatures(int *temperatures, int temperaturesSize, int *returnSize) {
int *ans = (int *)malloc(sizeof(int) * temperaturesSize);
*returnSize = temperaturesSize;
struct Stack stack = {NULL};
for (int i = 0; i < temperaturesSize; i++) {
while (stack.top != NULL && temperatures[i] > temperatures[peek(&stack)]) {
int index = pop(&stack);
ans[index] = i - index;
}
push(&stack, i);
}
while (stack.top != NULL) {
int index = pop(&stack);
ans[index] = 0;
}
return ans;
}
int main() {
int temperaturesSize;
scanf("%d", &temperaturesSize);
int *temperatures = (int *)malloc(sizeof(int) * temperaturesSize);
for (int i = 0; i < temperaturesSize; i++) {
scanf("%d", &temperatures[i]);
}
int returnSize;
int *ans = dailyTemperatures(temperatures, temperaturesSize, &returnSize);
for (int i = 0; i < returnSize; i++) {
printf("%d ", ans[i]);
}
printf("\n");
free(temperatures);
free(ans);
return 0;
}
```
该算法的时间复杂度为 O(n),其中 n 为数组长度。
阅读全文