【发布时间】:2016-05-07 19:20:46
【问题描述】:
我被赋予了这个任务来解决:
编写一个程序,读取一个整数数组并从中删除最少数量的元素,使剩余数组按升序排序。打印为使数组排序而需要删除的最少元素数。
时间限制 0.1 秒。
样本测试:
输入:
1, 4、 3、 3、 6、 3、 2、 3
输出:
3
不幸的是,我的程序比较慢。这是我的代码:
using System;
static bool CheckAscending(List<int> list)
{
bool ascending = true;
for (int i = 0; i < list.Count - 1; i++)
{
if (list[i] > list[i + 1])
{
ascending = false;
}
}
return ascending;
}
static void Main()
{
int n;
n = int.Parse(Console.ReadLine());
List<int> arr = new List<int>();
List<int> sorted = new List<int>();
int maxSubsetLenght = 0;
for (int i = 0; i < n; i++)
{
arr.Add(int.Parse(Console.ReadLine()));
}
for (int i = 1; i <= (int)Math.Pow(2, n) - 1; i++)
{
int tempSubsetLenght = 0;
List<int> temp = new List<int>();
for (int j = 1; j <= n; j++)
{
if (((i >> (j - 1)) & 1) == 1)
{
temp.Add(arr[j - 1]);
tempSubsetLenght++;
}
}
if ((tempSubsetLenght > maxSubsetLenght) && (CheckAscending(temp)))
{
sorted = temp;
maxSubsetLenght = tempSubsetLenght;
}
}
Console.WriteLine(n - sorted.Count);
}
有人可以帮我加快我的程序吗?如果您能在不久的将来回答,我会很高兴。
【问题讨论】:
-
这像是一个作业?
-
是的,就像一个任务。但我需要改进我的程序才能更快。
-
嗯,我试过了,但我认为这是不可能的,因为你需要从列表中删除、检查并分配值。