基础算法----找出集合中和值为指定值的两个数

思想

假定集合为有序集合,对于有序集合来讲,和值大于指定值则后位前移,不然则前位后移;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

相关文章
相关标签/搜索