假定集合爲有序集合,對於有序集合來講,和值大於指定值則後位前移,不然則前位後移;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