228. Summary Ranges


228. Summary Ranges My Submissions
Question
Total Accepted: 36554 
Total Submissions: 159532 
Difficulty: Easy
Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given  [0,1,2,4,5,7] , return  ["0->2","4->5","7"].
Credits: Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide Tags
 
Array
Show Similar Problems
分析:
文字列の素朴なシミュレーション思想は,構想がはっきりしている.
class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> result;
        int i=0;
        while(i<nums.size())
        {
            string ans=to_string(nums[i]);
            bool flag=false;
            // ,    
            if( ++i < nums.size() && nums[i]==(nums[i-1]+1) )//     
              {  
                  ans.append("->");
                  flag=true;//      
              }
            // ,          
            while(flag && i<nums.size())
            {
                if(nums[i]!=nums[i-1]+1)
                   break;
                i++; 
            }
            // ,        
            if(flag)
                ans.append(to_string(nums[i-1]));
            result.push_back(ans);    
        }
        return result;
    }
};

他の人のアルゴリズム設計を学ぶ:
(ダブルポインタ)
class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> result;
        for (int i = 0; i < nums.size();) //    
        {
            int start = i, end = i;//       
            while (end + 1 < nums.size() && nums[end+1] == nums[end] + 1) //         
                end++;
            if (end > start) 
                result.push_back(to_string(nums[start]) + "->" + to_string(nums[end]));
            else 
                result.push_back(to_string(nums[start]));
            i = end+1;
        }
        return result;
    }
};

注:本博文はEbowTangオリジナルで、その後も本論文を更新する可能性があります.転載する場合は、必ずこの情報をコピーしてください!
原文住所:http://blog.csdn.net/ebowtang/article/details/50649914
原作者ブログ:http://blog.csdn.net/ebowtang