简体   繁体   English

遍历两个数组时如何优化时间复杂度

[英]How to optimize the time complexity when looping over two arrays

I have 2 sorted arrays of application names in the user's Android device.我在用户的 Android 设备中有 2 个排序的应用程序名称数组。 I now need to log an event if one array contains at least one item of the other array.如果一个数组至少包含另一个数组的一项,我现在需要记录一个事件。

Here is my code:这是我的代码:

  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;
  }

this approach finds similar strings in O(n):这种方法在 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;
  }
}

You could potentially use Set as it has O(1) complexity for read operation.您可能会使用 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;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM