解题思路
-
基本思路:
- 使用数组记录每天的价格
- 遍历数组找出价格变化的分界点
- 合并相同价格的连续天数
-
实现方法:
- 先将所有价格信息存入数组
- 遍历数组找出价格变化点
- 生成最终的区间结果
代码
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
string handle(int prices[], int size) {
string result;
int i = 0;
int lastDay = 0;
while (i < size) {
int currentPrice = prices[i];
i++;
while (i < size && currentPrice == prices[i]) {
i++;
}
int current = i;
if (prices[current - 1] != 0) {
if (!result.empty()) {
result += ",";
}
result += "[" + to_string(lastDay) + ", " +
to_string(current - 1) + ", " +
to_string(prices[current - 1]) + "]";
}
lastDay = i;
}
return result;
}
};
int main() {
int prices[12000] = {0}; // 初始化为0
int start, end, price;
while (cin >> start >> end >> price) {
for (int i = start; i <= end; i++) {
prices[i] = price;
}
}
Solution solution;
cout << solution.handle(prices, 12000) << endl;
return 0;
}
import java.util.*;
public class Main {
public static String handle(int[] prices) {
StringBuilder buf = new StringBuilder();
int size = prices.length;
int i = 0;
int lastDay = 0;
while (i < size) {
int currentPrice = prices[i];
i++;
while (i < size && currentPrice == prices[i]) {
i++;
}
int current = i;
if (prices[current - 1] != 0) {
if (buf.length() > 0) {
buf.append(",");
}
buf.append("[").append(lastDay).append(", ")
.append(current - 1).append(", ")
.append(prices[current - 1]).append("]");
}
lastDay = i;
}
return buf.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] prices = new int[12000]; // 初始化为0
while (sc.hasNext()) {
int start = sc.nextInt();
int end = sc.nextInt();
int price = sc.nextInt();
for (int i = start; i <= end; i++) {
prices[i] = price;
}
}
System.out.print(handle(prices));
}
}
class Solution:
def handle(self, prices):
size = len(prices)
i = 0
lastDay = 0
result = []
while i < size:
currentPrice = prices[i]
i += 1
while i < size and currentPrice == prices[i]:
i += 1
current = i
if prices[current - 1] != 0:
result.append(f"[{lastDay}, {current - 1}, {prices[current - 1]}]")
lastDay = i
return ",".join(result)
if __name__ == "__main__":
prices = [0] * 12000 # 初始化为0
try:
while True:
start, end, price = map(int, input().split())
for i in range(start, end + 1):
prices[i] = price
except:
pass
solution = Solution()
print(solution.handle(prices))
算法及复杂度
- 算法:数组遍历
- 时间复杂度:,其中 为天数
- 空间复杂度:,用于存储每天的价格