【发布时间】:2017-08-26 00:12:41
【问题描述】:
我正在考虑寻找三元组和的各种方法,我遇到了这个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
【问题讨论】:
-
提供一些示例输入并解释结果有什么问题。
-
@Jasen:编辑了问题并添加了我尝试过的输入。
标签: arrays algorithm binary-search