【发布时间】:2016-06-15 15:24:31
【问题描述】:
嗨,我有一个大小为 N 的数组。数组值总是只有 1、2、3 个整数值。现在我需要找到给定数组索引范围之间的最小数字。所以例如array = 2 1 3 1 2 3 1 3 3 2. [2-4] = 1、[4-5] = 2、[7-8] = 3 等范围的最小值。
下面是我的代码:
static void Main(String[] args) {
string[] width_temp = Console.ReadLine().Split(' ');
int[] width = Array.ConvertAll(width_temp,Int32.Parse); // Main Array
string[] tokens_i = Console.ReadLine().Split(' ');
int i = Convert.ToInt32(tokens_i[0]);
int j = Convert.ToInt32(tokens_i[1]);
int vehicle = width[i];
for (int beg = i+1; beg <= j; beg++) {
if (vehicle > width[beg]) {
vehicle = width[beg];
}
}
Console.WriteLine("{0}", vehicle);
}
上面的代码工作正常。但我担心的是效率。在上面我只取一组数组范围,但实际上会有 n 个范围,我必须返回每个范围的最低值。现在的问题是,如果有像 [0-N] 这样的范围,N 是数组大小,那么我最终会比较所有项目的最低值。所以我想知道是否有办法优化代码以提高效率???
【问题讨论】:
标签: c# loops c#-4.0 optimization comparison