Question

Formatted question description: https://leetcode.ca/all/228.html

 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"]
 Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.

 Example 2:

 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.

 @tag-array

Algorithm

Traverse the array once and check whether the next number is increasing each time

  • If yes, continue to traverse down
  • If not, we have to judge whether it is a number or a sequence at this time,
    • A number is directly stored in the result
    • The sequence should be stored in the first and last numbers and the arrow “->”.

We need two variables i and j, where i is the position of the starting number of the continuous sequence, j is the length of the continuous sequence, when j is 1, it means there is only one number, if it is greater than 1, it is a continuous sequence.

Code

Java

import java.util.ArrayList;
import java.util.List;

public class Summary_Ranges {

    class Solution {
        public List<String> summaryRanges(int[] nums) {
            List<String> result = new ArrayList<>();
            int left = 0, n = nums.length;
            while (left < n) {
                int right = 1;
                while (left + right < n && (long)nums[left + right] - nums[left] == right) {
                    ++right;
                }
                result.add(
                    right <= 1 ?
                        String.valueOf(nums[left])
                        : String.valueOf(nums[left]) + "->" + String.valueOf(nums[left + right - 1]));
                left += right;
            }

            return result;

        }
    }
}

All Problems

All Solutions