O(N+M) time complexity

后端 未结 3 1134
孤街浪徒
孤街浪徒 2021-02-12 09:52

I\'m working through some practice problems where I\'m given a target time complexity and space complexity. One of them gives a target time complexity of O(N+M). I\'m having som

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-12 10:34

    A simple example of algorithm that is O(m+n):

    int sum(int[] nArr, int[] mArr) {
        int sum = 0;
        for(int i : nArr) {
            sum += i;
        }
        for(int i : mArr) {
            sum += i;
        }
        return sum;
    }
    

    To compute the sum, you need to go through all elements in nArr (size n) and all elements in mArr (size m), so the overall complexity is O(m+n)

提交回复
热议问题