finding a pair of integers in a sorted array which sum to K

前端 未结 2 1882
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-19 22:35

Given a sorted array of integers, how can we find a pair of integers that sum to K?

e.g. array = 1,3,5,6,10, K = 6, the answer is 1 and 5.<

2条回答
  •  渐次进展
    2021-01-19 22:58

    There is a linear (O(n)) solution.

    Take a hashtable and while iterating through the array check if the current element is already in the hashtable - if so then you've found the answer. Otherwise insert the number which is equal to K minus the current element. Works for non sorted array, btw.

    int[] ar = new int[] { 1, 4, 3, 5 };
    int K = 6;
    
    HashSet set = new HashSet();
    foreach (int a in ar)
    {
        if (set.Contains(a))
        {
            Console.WriteLine(a + ", " + (K - a));
            break;
        }
    
        set.Add(K - a);
    }
    

提交回复
热议问题