我目前有一些包含以下值的数组
var array = new[] { 4, 7, 9, 3, 8, 6, 4, 3, 3, 9};
我需要删除最小值和最大值的重复项,因此在这种情况下,最终产品将是
var array = new[] { 4, 7, 9, 3, 8, 6, 4};
答案 0 :(得分:5)
var ar = new[] { 4, 7, 9, 3, 8, 6, 4, 3, 3, 9 };
var max = ar.Max();
var min = ar.Min();
var bmin = 0;
var bmax = 0;
var res = ar.Where(i => (i > min || 0 == bmin++) && (i < max || 0 == bmax++));
答案 1 :(得分:2)
如果表现不是一个问题那么这样的事情就可以了
var min = arr.Min();
var max = arr.Max();
bool foundMin = false, foundMax = false;
var result = arr
.Where(a=>!((a==min && foundMin) || (a==max &&foundMax)))
.Select(a=>{
if(a==min)
{
foundMin = true;
}
else if(a==max)
{
foundMax = true;
}
return a;
}).ToArray();
我想不到用不到两次传球做到这一点的方法,所以我能看到的唯一改进就是做一个循环来同时找到最小值和最大值
int min,max;
for(int i=0;i<arr.length;i++)
{
if(i==0) min = max = arr[i];
else if(arr[i]<min)
{
min = arr[i];
}
else if (arr[i]>max)
{
max = arr[i];
}
}
但是如果你不关心性能就会使用内置的linq方法只是因为代码较少,但只有在不考虑性能的情况下才会这样做
作为常规循环
//assuming calculated min & max with loop or .Min & .Max linq extensions
var newLs = new List<int>();
int[] result;
bool foundMin = false, foundMax = false;
foreach(var val in arr)
{
if(val == min)
{
if(foundMin) continue;
foundMin = true;
}
if(val == max)
{
if(foundMax) continue;
foundMax = true;
}
newLs.Add(val);
}
result = newLs.ToArray();
答案 2 :(得分:1)
---------------------被修改------------------------- ----
////Correct
Int32[] arr = { 4, 7, 9, 3, 8, 6, 4, 3, 3, 9 };
List<Int32> newArr = new List<Int32>();
Int32 max = arr.Max();
Int32 min = arr.Min();
Boolean removeMax = false;
Boolean removeMin = false;
foreach (var each in arr)
{
if (each == min || each == max)
{
if (!removeMax || !removeMin)
{
if (each == min)
{
newArr.Add(each);
removeMin = true;
}
if (each == max)
{
newArr.Add(each);
removeMax = true;
}
}
}
else
{
newArr.Add(each);
}
}
var arrAfter = newArr.ToArray();
答案 3 :(得分:1)
这只需要迭代array
两次。
var max = int.MinValue;
var min = int.MaxValue;
var array = new [] { 4, 7, 9, 3, 8, 6, 4, 3, 3, 9 };
// Get min and max values. With just one iteration.
foreach (var element in array)
{
if (element < min)
{
min = element;
}
if (max < element)
{
max = element;
}
}
var minCount = 0;
var maxCount = 0;
var list = array.ToList ();
// Search for duplicates with second iteration.
for (int i = 0; i < list.Count; ++i)
{
if (list[i] == min)
{
if (minCount++ != 0)
{
list.RemoveAt (i--);
}
continue;
}
if (list[i] == max)
{
if (maxCount++ != 0)
{
list.RemoveAt (i--);
}
}
}
array = list.ToArray ();