Check for missing number in sequence

前端 未结 14 1561
太阳男子
太阳男子 2020-12-04 17:58

I have an List which contains 1,2,4,7,9 for example.

I have a range from 0 to 10.

Is there a way to determine what numbers are missin

14条回答
  •  情话喂你
    2020-12-04 18:04

    this method here returns the number of missing elements ,sort the set , add all elements from range 0 to range max , then remove the original elements , then you will have the missing set

    int makeArrayConsecutive(int[] statues) 
    {
    
    Array.Sort(statues);    
    HashSet set = new HashSet();
    
    for(int i = statues[0]; i< statues[statues.Length -1]; i++)
     {
      set.Add(i);
     }
    
    for (int i = 0; i < statues.Length; i++)
    {
     set.Remove(statues[i]);
    }
    
    var x = set.Count;    
    return x;
    // return set ; // use this if you need the actual elements + change the method return type        
    }
    

提交回复
热议问题