美文网首页
228. Summary Ranges

228. Summary Ranges

作者: FlynnLWang | 来源:发表于2016-12-27 10:10 被阅读0次

    Question

    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"].

    Code

    public class Solution {
        public List<String> summaryRanges(int[] nums) {
            List<String> result = new ArrayList<>();
            if (nums == null || nums.length == 0) return result;
            if (nums.length == 1) {
                result.add(String.valueOf(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 (nums[i] == a) {
                    result.add(String.valueOf(a));
                } else {
                    result.add(a + "->" + nums[i]);
                }
            }
            return result;
        }
    }
    

    Solution

    很常规的思路,for循环中不断寻找符合条件的首数字和尾数字即可。

    相关文章

      网友评论

          本文标题:228. Summary Ranges

          本文链接:https://www.haomeiwen.com/subject/vwbsvttx.html