java solution with O(n)


  • 0
    M

    public List<String> summaryRanges(int[] nums) {
    List<String> result = new ArrayList<String>();
    if(nums == null || nums.length == 0) return result;
    int start = 0;
    int end = 0;
    int len = nums.length;
    int index = 0;
    while(index < len) {
    start = index;
    end = index;
    while(++index < len && (nums[index] - nums[index-1]) == 1) {
    end = index;
    }
    //index++;
    StringBuilder sb = new StringBuilder();
    if(start == end) {
    sb.append(nums[start]);
    } else {
    sb.append(nums[start]);
    sb.append("->");
    sb.append(nums[end]);
    }
    result.add(sb.toString());
    }
    return result;
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.