使用二进制搜索的三元组和

时间:2017-03-31 16:25:30

标签: arrays algorithm binary-search

我正在考虑找到三元组总和的各种方法,我遇到了这个finding a triplet having a given sum。所以我想试一试。

My algorithm:
1) Sort the numbers //O(nlogn)
2) Initialize low=0 and high=size-1
3) loop till low<high
   a) if sum-arr[high]-arr[low]< 0 , then decrement high
   b) if third number is not in range of (low,high) then break the loop
   c) else search for third number using binary search

但我没有得到正确的输出。我不知道我的逻辑错在哪里,因为它非常简单的二进制搜索。以下是我实施的内容。 请让我知道我的错误

static boolean isTriplet(int a[], int size, int sum)
    {
       Arrays.sort(a);  //sort the numbers

        int low = 0;
        int high = size-1;
        while(low<high)
        {

            int third = sum - a[high] - a[low];
            if(third<0)
                high--;
            else if(!(sum - a[high] - a[low]>a[low] && sum - a[high] - a[low]< a[high]))  //if the number is not within the range then no need to find the index
                break;
            else
            {
                int index = binarySearch(a,low+1,high-1,third);
                if(index != -1)
                {
                    System.out.println(a[low]+" "+a[index]+" "+a[high]);
                    return true;
                }
                else
                low++;                  

            }

        }
        return false;
    }

我尝试使用输入{1,2,3,4,5,6}和sum = 6但是它返回false,当输入为{3,4,8,1,2,7,5}且sum = 20时返回true

1 个答案:

答案 0 :(得分:0)

我部分理解你的想法,而不是完全理解。看起来你正试图解决O(n log(n))时间复杂度的问题,我不相信它是可能的。我不确定你是怎么做的:

           else
            low++; 

我怀疑在某些情况下你应该做什么

high--

那里。我也不确定这段代码:

if(third<0)
   high--;

如果第三个&gt; 0,但它低于低?

我读了另一个问题,它提出了一个O(n ^ 2 logn)解决方案,所以我在这里提供了这样一个解决方案(用Java)。

这个想法是:通过所有元素对迭代2个嵌套for循环(i,j),并查找第三个元素,它将补充数组其余部分中的三元组(使用二进制搜索完成查找 - while循环。

public class TripletSum {
    static boolean solve(int[] a, int k) {
        Arrays.sort(a);
        int n = a.length;

        for(int i = 0; i < n; i++) {
            for(int j = i + 1; j < n; j++) {
                int low = j + 1, high = n - 1;

                while(low <= high) {
                    int middle = (low + high) / 2;
                    int sum = a[middle] + a[i] + a[j];
                    if(sum == k) {
                        return true;
                    }
                    if(sum > k) {
                        high = middle - 1;
                    }
                    if(sum < k) {
                        low = middle + 1;
                    }
                }

            }
        }

        return false;
    }

    public static void main(String[] args) {
        int[] a = {1,2,3,4,5,6};

        System.out.println(solve(a, 20));
    } 
}

编辑: 我做了一些研究,无法找到解决这个问题的O(N logN)解决方案。原来这个问题很受欢迎,因为3SUM。您可以在Wiki page上看到有一个Quadratic解决方案,它击败了O(N ^ 2 logN)。