###### tags: `Leetcode` `easy` `array` `python` `c++` # 228. Summary Ranges ## [題目連結:] https://leetcode.com/problems/summary-ranges/description/ ## 題目: You are given a **sorted unique** integer array ```nums```. A **range** ```[a,b]``` is the set of all integers from ```a``` to ```b``` (inclusive). Return the **smallest sorted** list of ranges that **cover all the numbers in the array exactly**. That is, each element of ```nums``` is covered by exactly one of the ranges, and there is no integer ```x``` such that ```x``` is in one of the ranges but not in ```nums```. Each range ```[a,b]``` in the list should be output as: * ```"a->b"``` if ```a != b``` * ```"a"``` if ```a == b``` **Example 1:** ``` Input: nums = [0,1,2,4,5,7] Output: ["0->2","4->5","7"] Explanation: The ranges are: [0,2] --> "0->2" [4,5] --> "4->5" [7,7] --> "7" ``` **Example 2:** ``` Input: nums = [0,2,3,4,6,8,9] Output: ["0","2->4","6","8->9"] Explanation: The ranges are: [0,0] --> "0" [2,4] --> "2->4" [6,6] --> "6" [8,9] --> "8->9" ``` ## 解題想法: * 此題為給一已排序好的數列,求出連續的序列,並將其首尾兩數字之間用"->"連接 * Linear遍歷數組即可: * 需額外加入個正無窮於數組尾,避免原數組最後一個數字沒判斷到 * startPos=0: 用以記錄連續區間的起始位置 ## Python: ``` python= class Solution(object): def summaryRanges(self, nums): """ :type nums: List[int] :rtype: List[str] """ n=len(nums) if n==0: return [] #額外加入個正無窮 nums.append(float("inf")) res=[] startPos=0 #連續區間的起始位置 for i in range(n): #此i跑loop是不包含無限大的length 確保不會超出array #不連續才要進行裁斷 if (nums[i+1]-nums[i])!=1: res.append(str(nums[i]) if i==startPos else "%d->%d" %(nums[startPos], nums[i])) startPos=i+1 #將區間往後紀錄 return res if __name__ == '__main__': result = Solution() nums = [0,1,2,4,5,7] ans = result.summaryRanges(nums) print(ans) #Input: nums = [0,1,2,4,5,7] #Output: ["0->2","4->5","7"] ``` ## C++: * The **to_string()** method accepts a value of any basic data type and converts it into a string * 添加**INT_MIN**整數最**小**, * 因為若使用INT_MAX: 其值為2147483647 * 則若nums=[2147483645,2147483646]此極端case,會無法正確輸出 ``` cpp= class Solution { public: vector<string> summaryRanges(vector<int>& nums) { int n=nums.size(); if (n==0) return {}; vector<string> res; nums.push_back(INT_MIN); int startPos=0; for (int i=0; i<n; i++){ if ((long(nums[i+1])-nums[i]) != 1){ res.push_back( (i==startPos? to_string(nums[i]): to_string(nums[startPos])+"->"+to_string(nums[i]))); startPos=i+1; } } return res; } }; ```