What does “O(1) access time” mean?

后端 未结 16 2243
栀梦
栀梦 2020-11-28 18:21

I have seen this term \"O(1) access time\" used to mean \"quickly\" but I don\'t understand what it means. The other term that I see with it in the same context is \"O(n) ac

16条回答
  •  眼角桃花
    2020-11-28 18:56

    Every answer currently responding to this question tells you that the O(1) means constant time (whatever it happens to measuring; could be runtime, number of operations, etc.). This is not accurate.

    To say that runtime is O(1) means that there is a constant c such that the runtime is bounded above by c, independent of the input. For example, returning the first element of an array of n integers is O(1):

    int firstElement(int *a, int n) {
        return a[0];
    }
    

    But this function is O(1) too:

    int identity(int i) {
        if(i == 0) {
            sleep(60 * 60 * 24 * 365);
        }
        return i;
    }
    

    The runtime here is bounded above by 1 year, but most of the time the runtime is on the order of nanoseconds.

    To say that runtime is O(n) means that there is a constant c such that the runtime is bounded above by c * n, where n measures the size of the input. For example, finding the number of occurrences of a particular integer in an unsorted array of n integers by the following algorithm is O(n):

    int count(int *a, int n, int item) {
        int c = 0;
        for(int i = 0; i < n; i++) {
            if(a[i] == item) c++;
        }
        return c;
    }
    

    This is because we have to iterate through the array inspecting each element one at a time.

提交回复
热议问题