算法:在一组集合中,取得第K小的值

来源:互联网 发布:简繁体批量转换软件 编辑:程序博客网 时间:2024/05/06 15:39
    class Calculate<T>    {        public List<List<T>> Lists;        public Calculate(List<List<T>> _Lists)        {            Lists = _Lists;        }        private List<T> UnionLists()        {            List<T> results = new List<T>();            for (int i = 0; i < Lists.Count; i++)            {                for (int j = 0; j < Lists[i].Count; j++)                {                    results.Add(Lists[i][j]);                }            }            results.Sort();            results = results.Distinct().ToList(); ;            return results;        }        public T getIndex(int K)        {            List<T> results = UnionLists();            return results.ElementAt(K-1);        }    }


 

 

 

            List<int> list1 = new List<int> { 5, 6, 10 };            List<int> list2 = new List<int> { 5, 6, 10 };            List<int> list3 = new List<int> { 8, 9, 12 };            List<int> list4 = new List<int> { 9, 13, 15 };            List<List<int>> list = new List<List<int>> { list1,list2,list3,list4};            Calculate<int> cal = new Calculate<int>(list);            Console.WriteLine(cal.getIndex(4));            Console.ReadLine();


 

0 0
原创粉丝点击