トリプレットの合計を見つけるためのさまざまなアプローチを考えていましたが、これを見つけたのは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}
と合計= 6でそれを試してみましたが、それはfalseを返し、入力が{3,4,8,1,2,7,5}
との和= 20だったとき、私は部分的にあなたの考えを理解
いくつかのサンプル入力を提供し、結果が間違っていることを説明してください。 – Jasen
@ジャセン:質問を編集し、試した入力を追加しました。 – Ankita