📌  相关文章
📜  检查排序后的数组是否可以分成总和为 k 的对

📅  最后修改于: 2022-05-13 01:57:51.519000             🧑  作者: Mango

检查排序后的数组是否可以分成总和为 k 的对

给定一个有序的整数数组和一个数 k,编写一个函数,如果给定的数组可以分成对,使得每对的和为 k,则返回 true。
预期时间复杂度 O(n) 和额外空间 O(1)。这个问题是以下问题的变体,但有一个不同的有趣解决方案,只需要 O(1) 空间。
检查一个数组是否可以分成总和可被 k 整除的对

例子:

Input: arr[] = {1, 3, 3, 5}, k = 6
Output: True
We can divide array into (1, 5) and (3, 3).
Sum of both of these pairs is 6.

Input: arr[] = {2, 5, 5, 5, 5, 8}, k = 10
Output: True
We can divide array into (2, 8), (5, 5) and 
(5, 5). Sum of all these pairs is 10.

我们强烈建议您最小化您的浏览器并首先自己尝试。

一个简单的解决方案是遍历每个元素 arr[i]。查找是否还有另一个尚未访问的元素,其值为 (k – arr[i])。如果没有这样的元素,则返回 false。如果找到一对,则将两个元素都标记为已访问。该解决方案的时间复杂度为 O(n 2并且需要 O(n) 额外空间。
更好的解决方案是使用散列。在这篇文章中给出的解决方案可以很容易地修改为工作。该解决方案的时间复杂度为 O9n),但它需要额外的哈希表空间。
一个有效的解决方案是使用此处方法 1 中讨论的中间相遇算法

1) Initialize two index variables
  (a) Initialize first to the leftmost index: l = 0
  (b) Initialize second  the rightmost index:  r = n-1
2) Loop while l < r.
  (a) If (A[l] + A[r] != k)  then return false
  (b) Else r--, l++

下面是上述算法的实现。

C++
// A C++ program to check if arr[0..n-1] can be divided
// in pairs such that every pair has sum k.
#include 
using namespace std;
  
// Returns true if arr[0..n-1] can be divided into pairs
// with sum equal to k.
bool canPairsSorted(int arr[], int n, int k)
{
   // An odd length array cannot be divided into pairs
   if (n & 1)
       return false;  
 
   // Traverse from both sides of array
   int l = 0, r = n-1;
   while (l < r)
   {
       // If array can be divided, then sum of current
       // elements must be sum
       if (arr[l] + arr[r] != k)
          return false;
 
       // Move index variables
       l++; r--;
   }
 
   return true;
}
 
/* Driver program to test above function */
int main()
{
    int arr[] = {1, 2, 3, 3, 3, 3, 4, 5};
    int n = 6;
    int n = sizeof(arr)/sizeof(arr[0]);
    canPairs(arr, n, k)? cout << "True": cout << "False";
    return 0;
}


Java
// Java program to check if arr[0..n-1] can be divided
// in pairs such that every pair has sum k.
 
class GFG {
 
// Returns true if arr[0..n-1] can be divided into pairs
// with sum equal to k.
    static boolean canPairs(int arr[], int n, int k) {
// An odd length array cannot be divided into pairs
        if (n == 1) {
            return false;
        }
 
// Traverse from both sides of array
        int l = 0, r = n - 1;
        while (l < r) {
            // If array can be divided, then sum of current
            // elements must be sum
            if (arr[l] + arr[r] != k) {
                return false;
            }
 
            // Move index variables
            l++;
            r--;
        }
 
        return true;
    }
 
// Drivers code
    public static void main(String[] args) {
        int arr[] = {1, 2, 3, 3, 3, 3, 4, 5};
        int k = 6;
        int n = arr.length;
        if (canPairs(arr, n, k)) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}
//This code contributed by 29AjayKumar


Python 3
# A Python3 program to check if arr[0..n-1] can be
# divided in pairs such that every pair has sum k.
 
# Returns true if arr[0..n-1] can be divided
# into pairs with sum equal to k.
def canPairsSorted(arr, n, k):
 
    # An odd length array cannot
    # be divided into pairs
    if (n & 1):
        return False;
     
    # Traverse from both sides of array
    l = 0; r = n - 1;
    while (l < r):
     
        # If array can be divided, then
        # sum of current elements must be sum
        if (arr[l] + arr[r] != k):
            return False;
     
        # Move index variables
        l = l + 1; r = r - 1;
     
    return True
 
# Driver Code
arr = [1, 2, 3, 3, 3, 3, 4, 5]
k = 6
n = len(arr)
if(canPairsSorted(arr, n, k)):
    print("True")
else:
    print("False");
 
# This code is contributed
# by Akanksha Rai


C#
// C# program to check if arr[0..n-1]
// can be divided in pairs such that
// every pair has sum k.
using System;
 
class GFG
{
 
// Returns true if arr[0..n-1]
// can be divided into pairs
// with sum equal to k.
static bool canPairs(int []arr, int n, int k)
{
    // An odd length array cannot
    // be divided into pairs
    if (n == 1)
    {
        return false;
    }
 
    // Traverse from both sides of array
    int l = 0, r = n - 1;
    while (l < r)
    {
        // If array can be divided,
        // then sum of current
        // elements must be sum
        if (arr[l] + arr[r] != k)
        {
            return false;
        }
 
        // Move index variables
        l++;
        r--;
    }
 
    return true;
}
 
// Driver code
public static void Main()
{
    int []arr = {1, 2, 3, 3, 3, 3, 4, 5};
    int k = 6;
    int n = arr.Length;
    if (canPairs(arr, n, k))
    {
        Console.Write("True");
    }
    else
    {
        Console.Write("False");
    }
}
}
 
// This code is contributed by PrinciRaj


PHP


Javascript


输出:

True