MrModest

Yandex - Intervals.cs

Jun 5th, 2021
718
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // [1,4,5,2,3,9,8,11,0] => "0-5,8-9,11" // [0,1,2,3,4,5,8,9,11]
  2. // [1,4,3,2] => "1-4"                   // [1,2,3,4]
  3. // [1,4] => "1,4"                    
  4. //
  5. // [1, 2, 3, 4, 5], 7]
  6.  
  7. private static string ParseToInterval(int[] nums)
  8. {
  9.     if (nums.Length == 0)
  10.     {
  11.         return string.Empty;
  12.     }
  13.    
  14.     Arrays.Sort(nums);
  15.    
  16.     var start = 0;
  17.     var prev = 0;
  18.     var current = 0;
  19.    
  20.     var strList = new List<string>();
  21.    
  22.     while(current < nums.Length)
  23.     {
  24.         current++;
  25.        
  26.         if (nums[current] - nums[prev] == 1) {
  27.             prev++;
  28.         }
  29.         else
  30.         {
  31.             strList.Add(start == prev ? nums[start].ToString() : $"{nums[start]}-{nums[prev]}");
  32.             start = current;
  33.             prev = current;
  34.         }
  35.     }
  36.    
  37.     strList.Add(start == prev ? nums[start].ToString() : $"{nums[start]}-{nums[prev]}");
  38.    
  39.     return string.Join(", ", strList);
  40. }
RAW Paste Data