基礎算法----找出集合中和值爲指定值的兩個數

思想

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

源碼

http://git.oschina.net/aspnet/Suan-Facode

相關文章
相關標籤/搜索