【问题标题】:How to optimize the time complexity when looping over two arrays遍历两个数组时如何优化时间复杂度
【发布时间】:2022-02-06 20:39:22
【问题描述】:

我在用户的 Android 设备中有 2 个排序的应用程序名称数组。如果一个数组至少包含另一个数组的一项,我现在需要记录一个事件。

这是我的代码:

  appsArray = ["cred","cult","hotstar","netflix","prime","splitwise","spotify"];
  _apps = [...]; // Apps in user's mobile

  bool _isQualityUser() {
    var result = '';
    for (var app in _apps) {
      result = appsArray.singleWhere((el) => app.appName.contains(el));
    }
    return result.isNotEmpty;
  }

我正在为其寻找优化的解决方案。如果有人可以提供帮助。

【问题讨论】:

  • 如果您的appsArray 是固定大小(即大小为7),那么您是否使此操作有效也没关系。视觉上你无法区分这一点。

标签: flutter loops dart optimization


【解决方案1】:

这种方法在 O(n) 中找到相似的字符串:

void main() {
  List<String> list1 = ["bc", "ab", "abb", "bb", "aa", "ff"];
  List<String> list2 = ["ab", "bb", "abc", "cb", "bc", "fg", "ff"];

  list1.sort();
  list2.sort();

  int index1 = 0;
  int index2 = 0;
  while (true) {
    if (list1[index1] == list2[index2]) {
      print(list1[index1]);
      index1 += 1;
      index2 += 1;
    } else if (list1[index1].compareTo(list2[index2]) < 0) {
      index1 += 1;
    } else {
      index2 += 1;
    }
    if (index1 == list1.length || index2 == list2.length) break;
  }
}

【讨论】:

    【解决方案2】:

    您可能会使用 Set,因为它的读取操作复杂度为 O(1)。

    var appNames = <String>{'cred', 'cult'};
    
    bool _isQualityUser() {
        var result = '';
        for (var app in _apps) {
          result = appNames.contains(app.appName);
        }
        return result.isNotEmpty;
      }
    

    【讨论】:

    • 这个问题明确地告诉他从 2 个数组开始,而不是集合
    • 据我了解,appNames 数组是自定义的,这意味着它可以更改为集合。即使您可以从仍然是 O(n) 复杂度的数组创建集合
    猜你喜欢
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 2022-07-01
    • 1970-01-01
    • 2014-10-01
    • 2023-03-21
    • 2021-06-24
    相关资源
    最近更新 更多