Leetcode——228. Summary Ranges

题目原址

https://leetcode.com/problems/summary-ranges/description/

题目描述

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

Example1:

Input: [0,1,2,4,5,7]
Output: [“0->2”,”4->5”,”7”]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.

Example2:

Input: [0,2,3,4,6,8,9]
Output: [“0”,”2->4”,”6”,”8->9”]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.

解题思路

给定一个数组,将连续的数字放在在一起存入List<String>集合中,连续的数字只存储第一个和最后一个,然后将第一和最后一个数字用->连接起来

  • 首先要判断如果给定的数组只有一个元素,则将这唯一的元素放在集合中,返回即可
  • 通过for循环遍历数组中的所有元素,因为要计算连续元素的第一个和最后一个,则第一个元素放在变量start中,然后使用while循环遍历元素,找到连续的最后一个元素
  • start元素与while找到的最后一个元素进行比较,如果while找到的元素与start元素相同,则说明这个元素在数组中没有连续的,则直接将其存放在集合中即可
  • 如果元素在数组中有连续的,则将start 拼接 "->" 和最后一个元素。

AC代码

class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> ret = new ArrayList<String>();
        if(nums.length == 1){
            ret.add(nums[0] + "");
            return ret; 
        }
        for(int i = 0; i < nums.length; i++) {
            int start = nums[i];
            while(i < nums.length - 1 && nums[i] + 1 == nums[i + 1]){
                i++;
            }
            if(start != nums[i])
                ret.add(start + "->" + nums[i]);
            else
                ret.add(start + "");
        }
        return ret;        
    }
}

猜你喜欢

转载自blog.csdn.net/xiaojie_570/article/details/80338192