C# solution O(n)


  • 0
    Y
        public class Solution {
            public IList<string> FindMissingRanges(int[] nums, int lower, int upper) {
                if(nums.Length==0)
                    return lower==upper?new List<string>(){lower.ToString()}: new List<string>(){lower.ToString()+"->"+upper.ToString()};
                var res=new List<string>();
                int i=0;
                //less than lower
                while(i<nums.Length-1&&nums[i]<lower)
                        i++;
                if(nums[i]>lower+1)
                    {res.Add(lower.ToString()+"->"+(nums[i]-1).ToString());}
                else if(nums[i]>lower)
                    {res.Add(lower.ToString());}
                //between lower and upper
                while(i<nums.Length-1&&nums[i]<=upper)
                {
                    if(nums[i+1]>nums[i]+2)
                        {res.Add((nums[i]+1).ToString()+"->"+(nums[i+1]-1).ToString());}
                    else if(nums[i+1]>nums[i]+1)
                        {res.Add((nums[i]+1).ToString());}
                    i++;
                }
                //after nums[length-1]
                if(nums[nums.Length-1]<upper)
                {
                   if(nums[nums.Length-1]+1<upper)
                    {res.Add((nums[nums.Length-1]+1).ToString()+"->"+upper.ToString());}
                   else
                    {res.Add(upper.ToString());}
                }
                return res;
                
            }
        }

Log in to reply
 

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