简体   繁体   English

下面是排序算法 O(n) 吗?

[英]Is below sorting algorithm O(n)?

Algorithm:算法:

  1. insert element counts in a map在地图中插入元素计数
  2. start from first element从第一个元素开始
  3. if first is present in a map, insert in output array (total number of count), increment first如果地图中存在第一个,则插入输出数组(计数的总数),首先递增
  4. if first is not in a map, find next number which is present in a map如果第一个不在地图中,则查找地图中存在的下一个数字

Complexity: O(max element in array) which is linear, so, O(n).复杂度:O(数组中的最大元素),它是线性的,所以,O(n)。

vector<int> sort(vector<int>& can) {
    unordered_map<int,int> mp;
    int first = INT_MAX;
    int last = INT_MIN;
    for(auto &n : can) {
        first = min(first, n);
        last = max(last, n);
        mp[n]++;
    }
    vector<int> out;
    while(first <= last) {
        while(mp.find(first) == mp.end()) first ++;
        int cnt = mp[first];
        while(cnt--) out.push_back(first);
        first++;
    }
    return out;
}

Complexity: O(max element in array) which is linear, so, O(n).复杂度:O(数组中的最大元素),它是线性的,所以,O(n)。

No, it's not O(n).不,这不是 O(n)。 The while loop iterates last - first + 1 times, and this quantity depends on the array's contents , not the array's length . while循环迭代last - first + 1次,这个数量取决于数组的内容,而不是数组的长度

Usually we use n to mean the length of the array that the algorithm works on.通常我们使用 n 来表示算法处理的数组的长度。 To describe the range (ie the difference between the largest and smallest values in the array), we could introduce a different variable r, and then the time complexity is O(n + r), because the first loop populating the map iterates O(n) times, the second loop populating the vector iterates O(r) times, and its inner loop which counts down from cnt iterates O(n) times in total.为了描述范围(即数组中最大值和最小值之间的差异),我们可以引入一个不同的变量 r,然后时间复杂度为 O(n + r),因为填充映射的第一个循环迭代 O( n) 次,填充向量的第二个循环迭代 O(r) 次,其从cnt倒计时的内部循环总共迭代 O(n) 次。

Another more formal way to define n is the "size of the input", typically measured in the number of bits that it takes to encode the algorithm's input.定义 n 的另一种更正式的方法是“输入的大小”,通常以编码算法输入所需的位数来衡量。 Suppose the input is an array of length 2, containing just the numbers 0 and M for some number M. In this case, if the number of bits used to encode the input is n, then the number M can be on the order of O(2 n ), and the second loop does that many iterations;假设输入是一个长度为 2 的数组,其中只包含一些数字 M 的数字 0 和 M。在这种情况下,如果用于对输入进行编码的位数是 n,那么数字 M 可以是 O 的数量级(2 n ),第二个循环进行了多次迭代; so by this formal definition the time complexity is exponential.所以根据这个正式定义,时间复杂度是指数级的。

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

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