力扣-228.汇总区间

AC Code

自己做出来的,代码写的很烂,但是也浅浅记录一下叭,下面有看答案思路写出来的双指针代码

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> ans;
        int n = nums.size();
        if(n == 1) ans.emplace_back(to_string(nums[0]));
        int i = 1;
        int front = 0;
        while( i < n){
            if(nums[i - 1] + 1 != nums[i]){
                string temp = "";
                if(front == i - 1){
                    temp = to_string(nums[front]);
                }
                else{
                    temp = to_string(nums[front]) + "->" + to_string(nums[i-1]);
                }
                front = i;
                ans.emplace_back(temp);
            }
            if(i == n - 1){
                string temp = "";
                if(front == i){
                    temp = to_string(nums[front]);
                }
                else{
                    temp = to_string(nums[front]) + "->" + to_string(nums[i]);
                }
                ans.emplace_back(temp);
            }
            i++;
        }
        return ans;
    }
};

力扣-228.汇总区间_第1张图片

双指针

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> ans;
        int n = nums.size();
        int i = 0;
        while( i < n){
            int left = i;
            i++;
            while(i < n && nums[i - 1] + 1 == nums[i]){
                i++;
            }
            int right = i - 1;
            string tmp = to_string(nums[left]);
            if(left < right) tmp += "->" + to_string(nums[right]);
            ans.emplace_back(tmp);
        }
        return ans;
    }
};

力扣-228.汇总区间_第2张图片

你可能感兴趣的:(LeetCode,leetcode,算法)