例如
int im = 20;
int[] MyList = new int[] {6,15,23,59,80,87,120};
我现在有一个数是 20 不在数组里面的。
现在要在数组里面找出两个数:一个是比20小的,一个是20大的。
也就是说,要获取数组里面的 15 和 23
数组里面的数一定是从小到大,有序排列的
请问这个怎么写?
不好意思,分数不多,已经全部献上了,谢谢大家
------解决方案--------------------------------------------------------
int im = 20;
int[] MyList = new int[] { 6, 15, 23, 59, 80, 87, 120 };
int 大 = MyList.OrderByDescending(x => x).Where(x => x > im).Min();
int 小 = MyList.OrderBy(x => x).Where(x => x < im).Max();
------解决方案--------------------------------------------------------
- C# code
int im = 20; int[] MyList = new int[] {6,15,23,59,80,87,120}; Array.Sort(MyList); for(int i =0;i <MyList.Length -1 ;i++) { if(MyList[i]<82 && MyList[i+1]>82){ MessageBox.Show(i.ToString()); } }
------解决方案--------------------------------------------------------
------解决方案--------------------------------------------------------
那你用二分法吧
------解决方案--------------------------------------------------------
二分法,应该不会慢
- C# code
int im = 20; int[] MyList = new int[] {6,15,23,59,80,87,120}; Array.Sort(MyList); int index = Array.BinarySearch(MyList, im); if (index < 0) { index = ~index; } Console.WriteLine( "Value >= {0} is {1}, value < {0} is {2}.", im, index == MyList.Length ? "not exists" : MyList[index].ToString(), index == 0 ? "not exists" : MyList[index - 1].ToString() );