📌  相关文章
📜  计算具有[a,b]范围之和的数组中的三元组数

📅  最后修改于: 2021-04-24 18:51:26             🧑  作者: Mango

给定一个由不同整数和范围[a,b]组成的数组,任务是计算具有在[a,b]范围内的和的三元组的数量。
例子:

Input : arr[] = {8, 3, 5, 2}
        range = [7, 11]
Output : 1
There is only one triplet {2, 3, 5}
having sum 10 in range [7, 11].

Input : arr[] = {2, 7, 5, 3, 8, 4, 1, 9}
        range = [8, 16]
Output : 36

一个幼稚的方法是运行三个循环,一个接一个地考虑所有三胞胎。找到每个三元组的总和,如果总和在给定范围[a,b]中,则增加计数。
下面是上述方法的实现:

C++
// C++ program to count triplets with
// sum that lies in given range [a, b].
#include 
 
using namespace std;
 
// Function to count triplets
int countTriplets(int arr[], int n, int a, int b)
{
    // Initialize result
    int ans = 0;
 
    // Fix the first element as A[i]
    for (int i = 0; i < n - 2; i++) {
 
        // Fix the second element as A[j]
        for (int j = i + 1; j < n - 1; j++) {
 
            // Now look for the third number
            for (int k = j + 1; k < n; k++)
 
                if (arr[i] + arr[j] + arr[k] >= a
                    && arr[i] + arr[j] + arr[k] <= b)
                    ans++;
        }
    }
 
    return ans;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 7, 5, 3, 8, 4, 1, 9 };
    int n = sizeof arr / sizeof arr[0];
    int a = 8, b = 16;
    cout << countTriplets(arr, n, a, b) << endl;
    return 0;
}


Java
// Java program to count triplets
// with sum that lies in given
// range [a, b].
import java.util.*;
 
class GFG
{
     
// Function to count triplets
public static int countTriplets(int []arr, int n,
                                int a, int b)
{
    // Initialize result
    int ans = 0;
 
    // Fix the first
    // element as A[i]
    for (int i = 0; i < n - 2; i++)
    {
 
        // Fix the second
        // element as A[j]
        for (int j = i + 1; j < n - 1; j++)
        {
 
            // Now look for the
            // third number
            for (int k = j + 1; k < n; k++)
            {
                if (arr[i] + arr[j] + arr[k] >= a &&
                    arr[i] + arr[j] + arr[k] <= b)
                    {ans++;}
            }
        }
    }
 
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 2, 7, 5, 3, 8, 4, 1, 9 };
    int n = arr.length;
    int a = 8, b = 16;
    System.out.println("" + countTriplets(arr, n,
                                        a, b));
}
}
 
// This code is contributed
// by Harshit Saini


Python3
# Python3 program to count
# triplets with sum that
# lies in given range [a, b].
 
# Function to count triplets
def countTriplets(arr, n, a, b):
     
    # Initialize result
    ans = 0
 
    # Fix the first
    # element as A[i]
    for i in range(0, n - 2):
         
        # Fix the second
        # element as A[j]
        for j in range(i + 1, n - 1):
 
            # Now look for
            # the third number
            for k in range(j + 1, n):
 
                if ((arr[i] + arr[j] + arr[k] >= a)
                and (arr[i] + arr[j] + arr[k] <= b)):
                        ans += 1
                         
    return ans
 
# Driver code
if __name__ == "__main__":
     
    arr = [ 2, 7, 5, 3, 8, 4, 1, 9 ]
    n = len(arr)
    a = 8; b = 16
    print(countTriplets(arr, n, a, b))
 
# This code is contributed
# by Harshit Saini


C#
// C# program to count triplets
// with sum that lies in given
// range [a, b].
using System;
 
class GFG
{
     
// Function to count triplets
public static int countTriplets(int []arr, int n,
                                int a, int b)
{
    // Initialize result
    int ans = 0;
 
    // Fix the first
    // element as A[i]
    for (int i = 0;
            i < n - 2; i++)
    {
 
        // Fix the second
        // element as A[j]
        for (int j = i + 1;
                j < n - 1; j++)
        {
 
            // Now look for the
            // third number
            for (int k = j + 1;
                    k < n; k++)
            {
                if (arr[i] + arr[j] + arr[k] >= a &&
                    arr[i] + arr[j] + arr[k] <= b)
                    {ans++;}
            }
        }
    }
 
    return ans;
}
 
// Driver Code
public static void Main()
{
    int[] arr = {2, 7, 5, 3, 8, 4, 1, 9};
    int n = arr.Length;
    int a = 8, b = 16;
    Console.WriteLine("" + countTriplets(arr, n,
                                        a, b));
}
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)


PHP
= $a &&
                    $arr[$i] + $arr[$j] + $arr[$k] <= $b)
                    $ans++;
        }
    }
 
    return $ans;
}
 
// Driver Code
$arr = array( 2, 7, 5, 3, 8, 4, 1, 9 );
$n = sizeof($arr);
$a = 8; $b = 16;
echo countTriplets($arr, $n, $a, $b) . "\n";
 
// This code is contributed
// by Akanksha Rai(Abby_akku)
?>


Javascript


C++
// C++ program to count triplets with
// sum that lies in given range [a, b].
#include 
 
using namespace std;
 
// Function to find count of triplets having
// sum less than or equal to val.
int countTripletsLessThan(int arr[], int n, int val)
{
    // sort the input array.
    sort(arr, arr + n);
 
    // Initialize result
    int ans = 0;
 
    int j, k;
 
    // to store sum
    int sum;
 
    // Fix the first element
    for (int i = 0; i < n - 2; i++) {
 
        // Initialize other two elements as
        // corner elements of subarray arr[j+1..k]
        j = i + 1;
        k = n - 1;
 
        // Use Meet in the Middle concept.
        while (j != k) {
            sum = arr[i] + arr[j] + arr[k];
 
            // If sum of current triplet
            // is greater, then to reduce it
            // decrease k.
            if (sum > val)
                k--;
 
            // If sum is less than or equal
            // to given value, then add
            // possible triplets (k-j) to result.
            else {
                ans += (k - j);
                j++;
            }
        }
    }
 
    return ans;
}
 
// Function to return count of triplets having
// sum in range [a, b].
int countTriplets(int arr[], int n, int a, int b)
{
 
    // to store count of triplets.
    int res;
 
    // Find count of triplets having sum less
    // than or equal to b and subtract count
    // of triplets having sum less than or
    // equal to a-1.
    res = countTripletsLessThan(arr, n, b) -
        countTripletsLessThan(arr, n, a - 1);
 
    return res;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 7, 5, 3, 8, 4, 1, 9 };
    int n = sizeof arr / sizeof arr[0];
    int a = 8, b = 16;
    cout << countTriplets(arr, n, a, b) << endl;
    return 0;
}


Java
// Java program to count triplets
// with sum that lies in given
// range [a, b].
import java.util.*;
 
class GFG
{
// Function to find count of
// triplets having sum less
// than or equal to val.
public static int countTripletsLessThan(int []arr,
                                        int n, int val)
{
    // sort the input array.
    Arrays.sort(arr);
 
    // Initialize result
    int ans = 0;
 
    int j, k;
 
    // to store sum
    int sum;
 
    // Fix the first element
    for (int i = 0; i < n - 2; i++)
    {
 
        // Initialize other two elements
        // as corner elements of subarray
        // arr[j+1..k]
        j = i + 1;
        k = n - 1;
 
        // Use Meet in the
        // Middle concept.
        while (j != k)
        {
            sum = arr[i] + arr[j] + arr[k];
 
            // If sum of current triplet
            // is greater, then to reduce it
            // decrease k.
            if (sum > val)
                k--;
 
            // If sum is less than or
            // equal to given value,
            // then add possible
            // triplets (k-j) to result.
            else
            {
                ans += (k - j);
                j++;
            }
        }
    }
 
    return ans;
}
 
    // Function to return count
    // of triplets having sum
    // in range [a, b].
    public static int countTriplets(int arr[], int n,
                                    int a, int b)
    {
     
        // to store count
        // of triplets.
        int res;
     
        // Find count of triplets
        // having sum less than or
        // equal to b and subtract
        // count of triplets having
        // sum less than or equal
        // to a-1.
        res = countTripletsLessThan(arr, n, b) -
            countTripletsLessThan(arr, n, a - 1);
     
        return res;
    }
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = {2, 7, 5, 3,
                8, 4, 1, 9};
    int n = arr.length;
    int a = 8, b = 16;
    System.out.println("" + countTriplets(arr, n,
                                        a, b));
}
}
 
// This code is contributed
// by Harshit Saini


Python3
# Python program to count
# triplets with sum that
# lies in given range [a, b].
 
# Function to find count of
# triplets having sum less
# than or equal to val.
def countTripletsLessThan(arr, n, val):
 
    # sort the input array.
    arr.sort()
 
    # Initialize result
    ans = 0
 
    j = 0; k = 0
 
    # to store sum
    sum = 0
 
    # Fix the first element
    for i in range(0,n-2):
 
        # Initialize other two
        # elements as corner
        # elements of subarray
        # arr[j+1..k]
        j = i + 1
        k = n - 1
 
        # Use Meet in the
        # Middle concept.
        while j != k :
            sum = arr[i] + arr[j] + arr[k]
             
            # If sum of current triplet
            # is greater, then to reduce it
            # decrease k.
            if sum > val:
                k-=1
 
            # If sum is less than or
            # equal to given value,
            # then add possible
            # triplets (k-j) to result.
            else :
                ans += (k - j)
                j += 1
    return ans
 
# Function to return
# count of triplets having
# sum in range [a, b].
def countTriplets(arr, n, a, b):
     
    # to store count of triplets.
    res = 0
 
    # Find count of triplets
    # having sum less than or
    # equal to b and subtract
    # count of triplets having
    # sum less than or equal to a-1.
    res = (countTripletsLessThan(arr, n, b) -
        countTripletsLessThan(arr, n, a - 1))
 
    return res
 
# Driver code
if __name__ == "__main__":
     
    arr = [ 2, 7, 5, 3, 8, 4, 1, 9 ]
    n = len(arr)
    a = 8; b = 16
    print(countTriplets(arr, n, a, b))
     
# This code is contributed by
# Harshit Saini


C#
// C# program to count triplets
// with sum that lies in given
// range [a, b].
using System;
 
class GFG
{
// Function to find count of
// triplets having sum less
// than or equal to val.
public static int countTripletsLessThan(int[] arr,
                                        int n, int val)
{
    // sort the input array.
    Array.Sort(arr);
 
    // Initialize result
    int ans = 0;
 
    int j, k;
 
    // to store sum
    int sum;
 
    // Fix the first element
    for (int i = 0; i < n - 2; i++)
    {
 
        // Initialize other two elements
        // as corner elements of subarray
        // arr[j+1..k]
        j = i + 1;
        k = n - 1;
 
        // Use Meet in the
        // Middle concept.
        while (j != k)
        {
            sum = arr[i] + arr[j] + arr[k];
 
            // If sum of current triplet
            // is greater, then to reduce it
            // decrease k.
            if (sum > val)
                k--;
 
            // If sum is less than or
            // equal to given value,
            // then add possible
            // triplets (k-j) to result.
            else
            {
                ans += (k - j);
                j++;
            }
        }
    }
 
    return ans;
}
 
    // Function to return count
    // of triplets having sum
    // in range [a, b].
    public static int countTriplets(int[] arr, int n,
                                    int a, int b)
    {
     
        // to store count
        // of triplets.
        int res;
     
        // Find count of triplets
        // having sum less than or
        // equal to b and subtract
        // count of triplets having
        // sum less than or equal
        // to a-1.
        res = countTripletsLessThan(arr, n, b) -
            countTripletsLessThan(arr, n, a - 1);
     
        return res;
    }
 
// Driver Code
public static void Main()
{
    int[] arr = {2, 7, 5, 3,
                8, 4, 1, 9};
    int n = arr.Length;
    int a = 8, b = 16;
    Console.WriteLine("" + countTriplets(arr, n,
                                        a, b));
}
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)


PHP
 $val)
                $k--;
 
            // If sum is less than or equal
            // to given value, then add possible
            // triplets (k-j) to result.
            else
            {
                $ans += ($k - $j);
                $j++;
            }
        }
    }
 
    return $ans;
}
 
// Function to return count of triplets
// having sum in range [a, b].
function countTriplets($arr, $n, $a, $b)
{
 
    // to store count of triplets.
    $res;
 
    // Find count of triplets having sum less
    // than or equal to b and subtract count
    // of triplets having sum less than or
    // equal to a-1.
    $res = countTripletsLessThan($arr, $n, $b) -
           countTripletsLessThan($arr, $n, $a - 1);
 
    return $res;
}
 
// Driver Code
$arr = array( 2, 7, 5, 3, 8, 4, 1, 9 );
$n = sizeof($arr);
$a = 8;
$b = 16;
echo countTriplets($arr, $n, $a, $b), "\n";
     
// This code is contributed by Sachin
?>


输出:
36

时间复杂度: O(n 3 )
一种有效的解决方案是首先找到在[a,b]范围内总和小于或等于上限b的三元组的数量。三胞胎的数量也将包括总和小于下限a的三胞胎。减去总数小于a的三元组的计数。最终结果是三元组的总数在[a,b]范围内。
算法如下:

要查找总和小于或等于给定值的三元组的计数,请参阅对总和小于给定值的三元组进行计数
下面是上述方法的实现:

C++

// C++ program to count triplets with
// sum that lies in given range [a, b].
#include 
 
using namespace std;
 
// Function to find count of triplets having
// sum less than or equal to val.
int countTripletsLessThan(int arr[], int n, int val)
{
    // sort the input array.
    sort(arr, arr + n);
 
    // Initialize result
    int ans = 0;
 
    int j, k;
 
    // to store sum
    int sum;
 
    // Fix the first element
    for (int i = 0; i < n - 2; i++) {
 
        // Initialize other two elements as
        // corner elements of subarray arr[j+1..k]
        j = i + 1;
        k = n - 1;
 
        // Use Meet in the Middle concept.
        while (j != k) {
            sum = arr[i] + arr[j] + arr[k];
 
            // If sum of current triplet
            // is greater, then to reduce it
            // decrease k.
            if (sum > val)
                k--;
 
            // If sum is less than or equal
            // to given value, then add
            // possible triplets (k-j) to result.
            else {
                ans += (k - j);
                j++;
            }
        }
    }
 
    return ans;
}
 
// Function to return count of triplets having
// sum in range [a, b].
int countTriplets(int arr[], int n, int a, int b)
{
 
    // to store count of triplets.
    int res;
 
    // Find count of triplets having sum less
    // than or equal to b and subtract count
    // of triplets having sum less than or
    // equal to a-1.
    res = countTripletsLessThan(arr, n, b) -
        countTripletsLessThan(arr, n, a - 1);
 
    return res;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 7, 5, 3, 8, 4, 1, 9 };
    int n = sizeof arr / sizeof arr[0];
    int a = 8, b = 16;
    cout << countTriplets(arr, n, a, b) << endl;
    return 0;
}

Java

// Java program to count triplets
// with sum that lies in given
// range [a, b].
import java.util.*;
 
class GFG
{
// Function to find count of
// triplets having sum less
// than or equal to val.
public static int countTripletsLessThan(int []arr,
                                        int n, int val)
{
    // sort the input array.
    Arrays.sort(arr);
 
    // Initialize result
    int ans = 0;
 
    int j, k;
 
    // to store sum
    int sum;
 
    // Fix the first element
    for (int i = 0; i < n - 2; i++)
    {
 
        // Initialize other two elements
        // as corner elements of subarray
        // arr[j+1..k]
        j = i + 1;
        k = n - 1;
 
        // Use Meet in the
        // Middle concept.
        while (j != k)
        {
            sum = arr[i] + arr[j] + arr[k];
 
            // If sum of current triplet
            // is greater, then to reduce it
            // decrease k.
            if (sum > val)
                k--;
 
            // If sum is less than or
            // equal to given value,
            // then add possible
            // triplets (k-j) to result.
            else
            {
                ans += (k - j);
                j++;
            }
        }
    }
 
    return ans;
}
 
    // Function to return count
    // of triplets having sum
    // in range [a, b].
    public static int countTriplets(int arr[], int n,
                                    int a, int b)
    {
     
        // to store count
        // of triplets.
        int res;
     
        // Find count of triplets
        // having sum less than or
        // equal to b and subtract
        // count of triplets having
        // sum less than or equal
        // to a-1.
        res = countTripletsLessThan(arr, n, b) -
            countTripletsLessThan(arr, n, a - 1);
     
        return res;
    }
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = {2, 7, 5, 3,
                8, 4, 1, 9};
    int n = arr.length;
    int a = 8, b = 16;
    System.out.println("" + countTriplets(arr, n,
                                        a, b));
}
}
 
// This code is contributed
// by Harshit Saini

Python3

# Python program to count
# triplets with sum that
# lies in given range [a, b].
 
# Function to find count of
# triplets having sum less
# than or equal to val.
def countTripletsLessThan(arr, n, val):
 
    # sort the input array.
    arr.sort()
 
    # Initialize result
    ans = 0
 
    j = 0; k = 0
 
    # to store sum
    sum = 0
 
    # Fix the first element
    for i in range(0,n-2):
 
        # Initialize other two
        # elements as corner
        # elements of subarray
        # arr[j+1..k]
        j = i + 1
        k = n - 1
 
        # Use Meet in the
        # Middle concept.
        while j != k :
            sum = arr[i] + arr[j] + arr[k]
             
            # If sum of current triplet
            # is greater, then to reduce it
            # decrease k.
            if sum > val:
                k-=1
 
            # If sum is less than or
            # equal to given value,
            # then add possible
            # triplets (k-j) to result.
            else :
                ans += (k - j)
                j += 1
    return ans
 
# Function to return
# count of triplets having
# sum in range [a, b].
def countTriplets(arr, n, a, b):
     
    # to store count of triplets.
    res = 0
 
    # Find count of triplets
    # having sum less than or
    # equal to b and subtract
    # count of triplets having
    # sum less than or equal to a-1.
    res = (countTripletsLessThan(arr, n, b) -
        countTripletsLessThan(arr, n, a - 1))
 
    return res
 
# Driver code
if __name__ == "__main__":
     
    arr = [ 2, 7, 5, 3, 8, 4, 1, 9 ]
    n = len(arr)
    a = 8; b = 16
    print(countTriplets(arr, n, a, b))
     
# This code is contributed by
# Harshit Saini

C#

// C# program to count triplets
// with sum that lies in given
// range [a, b].
using System;
 
class GFG
{
// Function to find count of
// triplets having sum less
// than or equal to val.
public static int countTripletsLessThan(int[] arr,
                                        int n, int val)
{
    // sort the input array.
    Array.Sort(arr);
 
    // Initialize result
    int ans = 0;
 
    int j, k;
 
    // to store sum
    int sum;
 
    // Fix the first element
    for (int i = 0; i < n - 2; i++)
    {
 
        // Initialize other two elements
        // as corner elements of subarray
        // arr[j+1..k]
        j = i + 1;
        k = n - 1;
 
        // Use Meet in the
        // Middle concept.
        while (j != k)
        {
            sum = arr[i] + arr[j] + arr[k];
 
            // If sum of current triplet
            // is greater, then to reduce it
            // decrease k.
            if (sum > val)
                k--;
 
            // If sum is less than or
            // equal to given value,
            // then add possible
            // triplets (k-j) to result.
            else
            {
                ans += (k - j);
                j++;
            }
        }
    }
 
    return ans;
}
 
    // Function to return count
    // of triplets having sum
    // in range [a, b].
    public static int countTriplets(int[] arr, int n,
                                    int a, int b)
    {
     
        // to store count
        // of triplets.
        int res;
     
        // Find count of triplets
        // having sum less than or
        // equal to b and subtract
        // count of triplets having
        // sum less than or equal
        // to a-1.
        res = countTripletsLessThan(arr, n, b) -
            countTripletsLessThan(arr, n, a - 1);
     
        return res;
    }
 
// Driver Code
public static void Main()
{
    int[] arr = {2, 7, 5, 3,
                8, 4, 1, 9};
    int n = arr.Length;
    int a = 8, b = 16;
    Console.WriteLine("" + countTriplets(arr, n,
                                        a, b));
}
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)

的PHP

 $val)
                $k--;
 
            // If sum is less than or equal
            // to given value, then add possible
            // triplets (k-j) to result.
            else
            {
                $ans += ($k - $j);
                $j++;
            }
        }
    }
 
    return $ans;
}
 
// Function to return count of triplets
// having sum in range [a, b].
function countTriplets($arr, $n, $a, $b)
{
 
    // to store count of triplets.
    $res;
 
    // Find count of triplets having sum less
    // than or equal to b and subtract count
    // of triplets having sum less than or
    // equal to a-1.
    $res = countTripletsLessThan($arr, $n, $b) -
           countTripletsLessThan($arr, $n, $a - 1);
 
    return $res;
}
 
// Driver Code
$arr = array( 2, 7, 5, 3, 8, 4, 1, 9 );
$n = sizeof($arr);
$a = 8;
$b = 16;
echo countTriplets($arr, $n, $a, $b), "\n";
     
// This code is contributed by Sachin
?>
输出:
36

时间复杂度: O(n 2 )
辅助空间: O(1)