Wednesday, February 17, 2016

Leetcode: Summary Ranges


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

Runtime Analysis:

Runtime: O(n)

Algorithmic Approach:

This is an easy question. Since the ranges are all continuous integers, we just need traverse the array and compare each element with its previous, if they are not consecutive, the current number belongs to a new range. In my code, the start and end of the current range is maintained. Don't forget to consider a single number range and the slightly different output format required in this question.

Java Code:













































public class Solution { public List<String> summaryRanges(int[] nums) { int start = 0, end = 0; List<String> toRet = new ArrayList<String>(); String str = ""; if(nums.length == 0) return toRet; for(int i = 0; i < nums.length - 1; i++){ // if consecutive if(nums[i] + 1 == nums[i + 1]){ end++; // if the start, adds the string if(i == start){ str = nums[i] + ""; } } // if not consecutive else{ if(start != end){ str += "->" + nums[i]; } else{ str = nums[i] + ""; } toRet.add(str); start = i+1; end = i+1; } } // covers the last element if(start == end){ toRet.add(nums[end]+""); } else{ str += "->" + nums[end]; toRet.add(str); } return toRet; } }

No comments:

Post a Comment