C# solution: corner cases and the overflow of int.


  • 0
    B
    public class Solution 
    {
        public IList<string> FindMissingRanges(int[] nums, int lower, int upper) 
        {
            var n = nums.Length;
    
            if (n == 0) 
            {
                if (upper == lower)           return new List<string>(){$"{lower}"};
                return new List<string>(){$"{lower}->{upper}"};
            }
    
            var result = new List<string>();
    
            if (nums[0] != lower)
            {
                if (nums[0] - lower == 1)
                {
                    result.Add($"{lower}");
                }
                else
                {
                    result.Add($"{lower}->{nums[0]-1}");
                }
            }
    
            for (int i = 1; i < n; i++)
            {
                var missingNumbers = (long)nums[i] - (long)nums[i-1];
    
                if (missingNumbers == 2)
                {
                    result.Add($"{nums[i-1]+1}");
                }
                else if (missingNumbers > 2)
                {
                    result.Add($"{nums[i-1]+1}->{nums[i]-1}");
                }
            }
    
            if (nums[n-1] != upper)
            {
                if (upper - nums[n-1] == 1)
                {
                    result.Add($"{upper}");
                }
                else
                {
                    result.Add($"{nums[n-1]+1}->{upper}");
                }
            }
    
            return result;
        }
    }
    

Log in to reply
 

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