LeetCode228.Summary Ranges problem solving

 228.Summary Ranges
Difficulty: Medium
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"].

1. The solution, the simplest, is traversal and judgment.

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

 
 
Although this algorithm is simple, it is not very efficient. It beats 5.3% of java submissions. This problem itself is not difficult, but it is basically divided into three categories. It seems to be in the second category? Well, there is an easier way in Python.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326861232&siteId=291194637
Recommended