Java very simple and intuitive solution


  • 1
    S
    public List<String> summaryRanges(int[] nums) {
            
            int start = 0;
            int end = 0;
            
            List<String> result = new ArrayList<String>();
            if(nums.length == 0) return result;
            
            for(int i=1; i<nums.length; i++)
            {
                if(nums[i] == nums[i-1] + 1)
                {
                    end = i;
                }
                else // Sequence toot gayi
                {
                    AddToResult(result, nums, start, end);
                    start = i;
                    end = i;
                }
            }
            
            // Take care of the last block when sequence ended
            AddToResult(result, nums, start, end);
            return result;
        }
        
        public void AddToResult(List<String> result, int[] nums, int start, int end)
        {
            String seq = null;
            if(start != end) seq = nums[start] + "->" + nums[end];
            else if(start == end) seq = nums[start]+ "";
            result.add(seq);
        }

  • 0

    the method should renamed to addToResult ^^


Log in to reply
 

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