C++ solution, easy to understand but difficult to write bug free


  • 0
    F
    vector<string> summaryRanges(vector<int>& nums) {
            vector<string> ret;
            if (nums.size() == 0) return ret;
            string s = to_string(nums[0]);
            int nt = nums[0] + 1, cnt = 0;
            for (int i = 1; i < nums.size(); i++) {
                if (nums[i] == nt) {
                    nt++;
                    cnt++;
                    if (i == nums.size() - 1) {
                        s += "->" + to_string(nt - 1);
                    }
                } else {
                    if (cnt > 0) s += "->" + to_string(nt - 1);
                    ret.push_back(s);
                    s = to_string(nums[i]);
                    nt = nums[i] + 1;
                    cnt = 0;
                }
            }
            ret.push_back(s);
            return ret;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.