将两个数字替换为列表中不超过 K 个数字的总和

问题描述 投票:0回答:1

我需要帮助来解决此任务。 给定一个整数数组

inputList
和整数
max
。我想创建一个数组,如果这些元素的总和不大于
max
,则每两个相邻元素都将被它们的总和替换。如果不存在这样的对,则输出原始列表。我们需要遍历一次数组。

List<int> replacedList(int max, List<int> inputList) {
  List<int> outputList = [];
  ...
  return outputList;
}

void main() {
  replacedList(5, [5, 1, 3, 3, 4]);
  replacedList(6, [2, 3, 1, 5, 4, 3]);
}

第一个示例中的输出列表将为 [5, 4, 3, 4],因为只有一对 (1+3 <= max which is 5) sutisfied the condition. In the second one will be [5, 6, 4, 3] (there are two pairs: 2 and 3, and 1 and 5)

arrays list dart
1个回答
0
投票

如果我正确理解需要什么,这就是解决方案

void main() {
  List<int> result = replacedList(6, [2, 3, 1, 5, 4, 3]);
  print(result);
}

List<int> replacedList(int max, List<int> inputList) {
  List<int> outputList = List.from(inputList);
  for (int i = 0; i < outputList.length - 1; i++) {
    if (outputList[i] + outputList[i + 1] <= max) {
      outputList[i] = outputList[i] + outputList[i + 1];
      outputList.removeAt(i + 1);
      if (i > 0) {
        i--;
      }
    }
  }
  return outputList;
}
© www.soinside.com 2019 - 2024. All rights reserved.