假定集合为有序集合,对于有序集合来讲,和值大于指定值则后位前移,不然则前位后移;git
int[] arr = { 1, 3, 5, 7, 9, 15 }; // 找出和值为10的数 static void findDi(int[] arr, int sum) { int start = 0; int end = arr.Length - 1; while (start < end) { if (arr[start] + arr[end] == sum) { System.Console.WriteLine("start:" + arr[start] + ",end:" + arr[end]); start++; } else if (arr[start] + arr[end] > sum) { end--; } else { start++; } } }
3,7 1,9.net