You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中Dart语言:如何将列表重复值移至匹配值相邻位置?

Flutter中Dart语言:将列表重复值移至匹配值相邻位置

给定列表:

List colour = ["peach","red","orange","yellow","white","pink","red","maroon"];

需要把重复的red移到第一个red的紧邻位置,最终得到:

["peach","red","red","orange","yellow","white","pink","maroon"]

Dart的List没有直接实现该功能的内置方法,我们可以自己写逻辑完成:

实现思路

  • 用Map记录每个元素第一次出现的索引位置
  • 遍历列表,遇到重复元素时,将其从当前位置移除,插入到首次出现位置的下一位
  • 移除元素后列表长度会变化,需要调整遍历索引避免跳过元素

具体代码

void main() {
  List colour = ["peach","red","orange","yellow","white","pink","red","maroon"];
  // 存储元素首次出现的索引
  Map<String, int> firstOccurrence = {};
  
  for (int i = 0; i < colour.length; i++) {
    String current = colour[i];
    if (firstOccurrence.containsKey(current)) {
      // 移除当前重复元素
      String duplicate = colour.removeAt(i);
      // 插入到首次出现位置的下一位
      colour.insert(firstOccurrence[current]! + 1, duplicate);
      // 索引回退,避免跳过后续元素
      i--;
    } else {
      firstOccurrence[current] = i;
    }
  }
  
  print(colour); // 输出: [peach, red, red, orange, yellow, white, pink, maroon]
}

这个逻辑也适用于多个重复值的场景,比如列表中有三个red,最终会把所有重复项都集中到首次出现位置的相邻处,形成连续的相同元素。

内容的提问来源于stack exchange,提问作者Chintan Harkhani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 20:12:49