228. Summary Ranges

Given a sorted integer array without duplicates, return the summary of its ranges.

Example 1:
Input: [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Example 2:
Input: [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]

Solution:array

思路:
Time Complexity: O(N) Space Complexity: O(1)

Solution Code:

class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> result = new ArrayList();
        
        if(nums.length == 1){
            result.add(nums[0] + "");
            return result;
        }
        
        for(int i = 0; i < nums.length; i++){
            int a = nums[i];
            while(i + 1 < nums.length && (nums[i + 1] - nums[i]) == 1){
                i++;
            }
            if(a != nums[i]){
                result.add(a + "->" + nums[i]);
            }else{
                result.add(a + "");
            }
        }
        return result;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。