對數組進行特定的從小到大的排序如將1,1,2,2,3,3,4,4,5,5,5,5,5,5排序成1,2,3,4,5,1,2,3,4,5,5,5,5,5

對數組進行特定的從小到大的排序
將1,1,2,2,3,3,4,4,5,5,5,5,5,5排序成1,2,3,4,5,1,2,3,4,5,5,5,5,5
具體實現的代碼如下:

 private void button1_Click(object sender, EventArgs e)
        {
            List<int> input = new List<int>() { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 5, 5, 5, 5 };
            List<int> output = sortList(input);
            MessageBox.Show(output.ToString());
        }
        static List<int> sortList(List<int> input)
        {
            Dictionary<int, List<int>> dict = input.AsEnumerable()
                .OrderBy(x => x)
                .GroupBy(x => x, y => y)
                .ToDictionary(x => x.Key, y => y.ToList());
            List<int> results = new List<int>();
            while (dict.Keys.Count > 0)
            {
                List<int> tempKeys = dict.Keys.ToList();
                foreach (int key in tempKeys)
                {
                    results.Add(key);
                    if (dict[key].Count == 1)
                    {
                        dict.Remove(key);
                    }
                    else
                    {
                        dict[key].RemoveAt(0);
                    }
                }
            }
            return results;
        }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章