What is the time complexity of the following code fragment?

I wrote the following code snippet to find range summaries, that is, when a sorted array of integers is given without any duplicates, it returns the summaries as:

/* IP: [0,1,2,4,5,7]
 * OP: ["0->2","4->5","7"]
 */

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> res;

        if(nums.empty())
            return res;

        for(int i=0; i<nums.size(); i++) {
            int lowerRange=nums[i];

            while(((i+1)<nums.size()) && (nums[i+1]-nums[i]==1))
                i++;

            int higherRange=nums[i];

            if(lowerRange!=higherRange) {
                string str=to_string(lowerRange)+"->"+to_string(higherRange);
                res.push_back(str);
            } else
                res.push_back(to_string(lowerRange));
        }

        return res;
    }
};

. , "" ( while) ( for). O (n ^ 2), . , , while i++, - "" , . - . , O (n). - , O (n ^ 2) O (n)?

+4
2

, , , , . . , O(n).

if :

for (i = 0; i < nums.size(); i++) {
    if ((i+1)<nums.size()) && (nums[i+1]-nums[i]==1)) {
        //
    } else {
        //
    }
}

, , lowerRange higherRange.

+2

, O (n) .

0

Source: https://habr.com/ru/post/1680916/


All Articles