Check for missing number in sequence

前端 未结 14 1565
太阳男子
太阳男子 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:16

    Using Unity i have tested two solutions on set of million integers. Looks like using Dictionary and two "for" loops gives better result than Enumerable.Except

    FindMissing1 Total time: 0.1420 (Enumerable.Except)
    FindMissing2 Total time: 0.0621 (Dictionary and two for loops)

    public static class ArrayExtension
    {
        public static T[] FindMissing1(T[] range, T[] values)
        {
            List result = Enumerable.Except(range, values).ToList();
            return result.ToArray();
        }
    
        public static T[] FindMissing2(T[] range, T[] values)
        {
            List result = new List();
            Dictionary hash = new Dictionary(values.Length);
            for (int i = 0; i < values.Length; i++)
                hash.Add(values[i], values[i]);
    
            for (int i = 0; i < range.Length; i++)
            {
                if (!hash.ContainsKey(range[i]))
                    result.Add(range[i]);
            }
    
            return result.ToArray();
        }
    }
    
    public class ArrayManipulationTest : MonoBehaviour
    {
        void Start()
        {
            int rangeLength = 1000000;
            int[] range = Enumerable.Range(0, rangeLength).ToArray();
            int[] values = new int[rangeLength / 5];
            int[] missing;
            float start;
            float duration;
    
            for (int i = 0; i < rangeLength / 5; i ++)
                values[i] = i * 5;
    
            start = Time.realtimeSinceStartup;
            missing = ArrayExtension.FindMissing1(range, values);
            duration = Time.realtimeSinceStartup - start;
            Debug.Log($"FindMissing1 Total time: {duration:0.0000}");
    
            start = Time.realtimeSinceStartup;
            missing = ArrayExtension.FindMissing2(range, values);
            duration = Time.realtimeSinceStartup - start;
            Debug.Log($"FindMissing2 Total time: {duration:0.0000}");
        }
    }
    

提交回复
热议问题