输入一组大于0的整数,删除其中所有重复出现的字,并要求满足如下条件:
- 越大的数最终位置尽可能靠前
- 优先满足较大的数靠前
例1
1, 5, 4, 9, 4, 3, 4, 8, 7, 6, 9, 8, 7, 1
1, 5, 4, 9, 4, 3, 4, 8, 7, 6, 9, 8, 7, 1
例2
8, 4, 7, 6, 4, 9, 7, 9
8, 4, 7, 6, 4, 9, 7, 9
实现:
Code
class Program
{
static void Main(string[] args)
{
//var numbers = new int[] { 8, 4, 7, 6, 4, 9, 7, 9 };
var numbers = new int[] { 1, 5, 4, 9, 4, 3, 4, 8, 7, 6, 9, 8, 7, 1 };
int index = 0;
var groups = from n in numbers
let i = new NumItem { Value = n, Index = index++, Cost = 0 }
group i by i.Value into g
orderby g.Key descending
select g;
var destNumbers = new List<NumItem>();
foreach (var valueGroup in groups)
{
var maxCostItem = valueGroup.First();
foreach (var num in valueGroup)
{
num.Cost = destNumbers.Count(i => i.Index < num.Index && i.Value > num.Value);
if (maxCostItem.Cost < num.Cost)
maxCostItem = num;
}
destNumbers.Add(maxCostItem);
}
destNumbers.Sort((i1, i2) => i1.Index - i2.Index);
Console.WriteLine(string.Join(" ",
destNumbers.Select(i => i.Value.ToString()).ToArray()));
}
}
class NumItem
{
public int Value { get; set; }
public int Index { get; set; }
public int Cost { get; set; }
public override string ToString()
{
return Index + " " + Value + " " + Cost;
}
}
代码比较简单,但写出这段代码还是费了点功夫,有兴趣的朋友可以自己练习一下。