【问题标题】:Dart - swap list item or pop item from listDart - 从列表中交换列表项或弹出项
【发布时间】:2020-07-21 15:13:05
【问题描述】:

使用 Dart,什么是遍历字符串列表以搜索特定字符串的好方法,当找到字符串时将其移动到列表的前面?

例如,如果要查找字母“b”。找到它,把它移到前面。

['a', 'b', 'c']
 => ['b',  'a', 'c']

对Dart不太了解,我用简单的for循环解决了

List<String> example = ['a', 'b', 'c'];
for (int i = 0; i< example.length; i++) {
  if (example[i] == 'b') {
      final temp = example[0];
      example[0] = example[i];
      example[i] = temp;
  }
}

在 dart 中是否有一种方法可以调用列表上的某个数组方法来查找特定项目,将其从原始列表中删除并返回已删除的项目?就像 JS 中的.splice()

【问题讨论】:

    标签: list dart


    【解决方案1】:

    List 数据结构的属性

    在解决这个问题时,了解列表数据结构的一些属性会很有帮助:

    • 更改索引的值很快。
    • 在列表末尾添加或删除项目很快。
    • 从列表的开头或中间删除项目很慢,因为它后面的所有项目都需要上移一个索引。
    • 将项目添加到列表的开头或中间很慢,因为它之后的所有项目都需要向后移动一个索引。

    删除和插入

    因此,尽管@FloW 的答案非常简洁易读,但速度很慢,因为它需要从列表中间删除并添加到列表开头:

    final example = ["a", "b", "c"];
    if (example.remove("b")) {
      example.insert(0, "b");
    }
    

    对于短列表,这可能无关紧要,但对于长列表,这可能会对性能产生显着影响。

    交换

    由于原始问题中的要求允许交换而不是删除和插入,因此我认为问题本身给出的 for 循环解决方案更好:

    List<String> example = ['a', 'b', 'c'];
    for (int i = 0; i < example.length; i++) {
      if (example[i] == 'b') {
        final temp = example[0];
        example[0] = example[i];
        example[i] = temp;
      }
    }
    

    虽然此搜索仍需要访问列表中的每个项目,但如果找到匹配项,则不需要移动所有内容。仅更改了两个受影响的索引。

    您可以通过在if 块的末尾添加break 语句来进一步提高效率,这相当于使用indexOf

    final example = ['a', 'b', 'c'];
    final value = 'b';
    final index = example.indexOf(value);
    example[index] = example[0];
    example[0] = value;
    

    【讨论】:

      【解决方案2】:

      用于列表删除然后插入以将其移到前面

      if(example.remove("b"))
            example.insert(0, "b");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-23
        • 2016-10-13
        • 1970-01-01
        • 1970-01-01
        • 2017-09-13
        • 2022-07-01
        • 1970-01-01
        • 2019-11-11
        相关资源
        最近更新 更多