希望这会奏效。刚刚测试了一下,效果很好。
int[] x = {2,5,6,9,45,48,54,76,97,102,134,203,234,245,267,289,299};
List<int> y = new List<int>();
for (int i = 0; i < x.Length; i++)
{
if ( (x[i] >= 31) && (x[i] <= 255) )
{
y.Add(x[i]);
}
}
所以我为x 使用了一个数组。然后我创建了一个名为y 的列表。我会使用循环来检查值是否满足条件。如果有,我会将它们添加到y 列表中。
foreach (int k in y)
{
Console.WriteLine(k);
}
使用此循环只是为了确保它有效(可选)。
下次请在发布问题之前表现出努力。此外,这是一个简单的算法,所以它都是关于循环的。只要您了解数组和循环的基础知识,即使是初学者程序员也应该知道这一点。欢迎使用 Stack Overflow。
Ansible 的回答(更高效)
但是因为这是一个有序数组,我们可以通过在超过上限后停止搜索来提高效率。我们知道这些数字都不会在我们的范围内。我们可以通过简单地打破 for 循环来做到这一点。
int[] x = {2,5,6,9,45,48,54,76,97,102,134,203,234,245,267,289,299};
List<int> y = new List<int>();
for (int i = 0; i < x.Length; i++)
{
if ( (x[i] >= 31) && (x[i] <= 255) )
{
y.Add(x[i]);
}
else if (x[i] > 255)
{
// We are past the upper bound, we are okay to stop the for loop now.
break;
}
}
但除此之外,我们还可以通过对下限进行二分搜索来提高效率。这样做不是从数组的开头开始遍历所有值,而是从中间开始。我们可以通过查看值 97(在数组中间)知道我们的下限必须在数组的前半部分。这已经将我们正在进行的搜索量分成了一半。我们可以继续这样做,将数组切成两半,直到找到我们正在寻找的值。
将它们放在一起看起来像这样。
int[] x = {2,5,6,9,45,48,54,76,97,102,134,203,234,245,267,289,299};
List<int> y = new List<int>();
int lowerBoundIndex = binarySearch(array, 0, x.length, 31);
for (int i = lowerBoundIndex; i < x.Length; i++)
{
if ( (x[i] >= 31) && (x[i] <= 255) )
{
y.Add(x[i]);
}
else if (x[i] > 255)
{
// We are past the upper bound, we are okay to stop the for loop now.
break;
}
}
public int binarySearch(int[] array, int lowerbound, int upperbound, int key) {
int position;
// To start, find the subscript of the middle position.
position = (lowerbound + upperbound) / 2;
while (!IsTargetIndex(array, position, key) && (lowerbound <= upperbound)) {
if (array[position] > key) // If the number is > key, ..
{ // decrease position by one.
upperbound = position - 1;
} else {
lowerbound = position + 1; // Else, increase position by one.
}
position = (lowerbound + upperbound) / 2;
}
if (lowerbound <= upperbound) {
return position;
}
return -1;
}
public boolean IsTargetIndex(int[] array, int position, int key)
{
int current = array[position];
int previous;
if (position == 0)
previous = -1;
else
previous = array[position -1];
if ((previous < key) && (current >= key))
{
return true;
}
return false;
}
二分搜索取自这里,但我不得不修改它,因为我们不是在寻找精确匹配,而是第一个大于或等于下限的项目。这是在 IsTargetIndex 中完成的。
这可能会也可能不会过分。如果您的阵列很小,那么这可能不会带来很大的性能提升。但是想象一下,如果您的阵列有数百万个节点,那么这可能会节省大量时间。
下次请在发布问题之前表现出努力。此外,这可以通过一个简单的算法来完成,所以这都是关于循环的。只要您了解数组和循环的基础知识,即使是初学者程序员也应该知道这一点。欢迎使用 Stack Overflow。