C# O(n)


  • 0
    Y
    public class Solution {
        public IList<string> SummaryRanges(int[] nums) {
            int n=nums.Length;
            var res=new List<string>();
            if(n < 1)
                return res;
            int rS=nums[0],sInd=0;
            StringBuilder sb=new StringBuilder();
            for(int i=1; i<n; i++)
            {
                if(nums[i]>nums[i-1]+1)
                {
                    sb=new StringBuilder();
                    sb.Append(rS.ToString());
                    if(i-1 != sInd)
                    {
                        sb.Append("->");
                        sb.Append(nums[i-1].ToString());
                    }
                    res.Add(sb.ToString());
                    rS = nums[i];
                    sInd = i;
                }
            }
            string endAdd = rS.ToString();
            if(sInd != n-1)
            {
                endAdd+="->";
                endAdd+=nums[n-1].ToString();
            }
            res.Add(endAdd);
            return res;
        }
    }

Log in to reply
 

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