📌  相关文章
📜  找到一个大小为 K 的子数组,其总和是一个完全平方数

📅  最后修改于: 2021-09-05 08:39:34             🧑  作者: Mango

给定一个数组arr[]和一个整数K ,任务是找到一个长度为K的子数组,其总和是一个完美的平方。如果不存在这样的子数组,则打印-1 。否则,打印子数组。

注意:可以有多个可能的子阵列。打印其中任何一个。
例子:

朴素方法:解决问题的最简单方法是生成大小为K 的所有可能子数组,并检查生成的任何子数组的总和是否为完全平方数。如果发现为真,则打印该子数组。如果没有子数组满足条件,则打印“-1”
时间复杂度: O(N*K)
辅助空间: O(K)

有效的方法:一种有效的方法是使用滑动窗口技术来查找大小为K的连续子数组的总和,然后使用二分搜索检查该总和是否为完全平方数。下面是解决这个问题的步骤:

  1. 计算前K 个数组元素的总和并将其存储在一个变量中,例如curr_sum
  2. 然后一一迭代剩余的数组元素,并通过添加i元素并从数组中删除第(i – K)元素来更新curr_sum
  3. 对于得到的每一个curr_sum值,检查它是否是一个完全平方数。
  4. 如果发现对于curr_sum 的任何值都为,则打印相应的子数组
  5. 否则,打印 -1。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to check if a given number
// is a perfect square or not
bool isPerfectSquare(int n)
{
    // Find square root of n
    double sr = sqrt(n);
 
    // Check if the square root
    // is an integer or not
    return ((sr - floor(sr)) == 0);
}
 
// Function to print the subarray
// whose sum is a perfect square
void SubarrayHavingPerfectSquare(
    vector arr, int k)
{
    pair ans;
    int sum = 0, i;
 
    // Sum of first K elements
    for (i = 0; i < k; i++) {
        sum += arr[i];
    }
 
    bool found = false;
 
    // If the first k elements have
    // a sum as perfect square
    if (isPerfectSquare(sum)) {
        ans.first = 0;
        ans.second = i - 1;
    }
    else {
 
        // Iterate through the array
        for (int j = i;
             j < arr.size(); j++) {
 
            sum = sum + arr[j] - arr[j - k];
 
            // If sum is perfect square
            if (isPerfectSquare(sum)) {
                found = true;
                ans.first = j - k + 1;
                ans.second = j;
            }
        }
 
        for (int k = ans.first;
             k <= ans.second; k++) {
            cout << arr[k] << " ";
        }
    }
 
    // If subarray not found
    if (found == false) {
        cout << "-1";
    }
}
 
// Driver Code
int main()
{
    // Given array
    vector arr;
 
    arr = { 20, 34, 51, 10,
            99, 87, 23, 45 };
 
    // Given subarray size K
    int K = 3;
 
    // Function Call
    SubarrayHavingPerfectSquare(arr, K);
 
    return 0;
}


Java
// Java program for
// the above approach
class GFG{
     
static class pair
{
  int first, second;
}
// Function to check if a given number
// is a perfect square or not
static boolean isPerfectSquare(int n)
{
  // Find square root of n
  double sr = Math.sqrt(n);
 
  // Check if the square root
  // is an integer or not
  return ((sr - Math.floor(sr)) == 0);
}
 
// Function to print the subarray
// whose sum is a perfect square
static void SubarrayHavingPerfectSquare(int[] arr,
                                        int k)
{
  pair ans = new pair();
  int sum = 0, i;
 
  // Sum of first K elements
  for (i = 0; i < k; i++)
  {
    sum += arr[i];
  }
 
  boolean found = false;
 
  // If the first k elements have
  // a sum as perfect square
  if (isPerfectSquare(sum))
  {
    ans.first = 0;
    ans.second = i - 1;
  }
  else
  {
    // Iterate through the array
    for (int j = i; j < arr.length; j++)
    {
      sum = sum + arr[j] - arr[j - k];
 
      // If sum is perfect square
      if (isPerfectSquare(sum))
      {
        found = true;
        ans.first = j - k + 1;
        ans.second = j;
      }
    }
 
    for (int k1 = ans.first;
             k1 <= ans.second; k1++)
    {
      System.out.print(arr[k1] + " ");
    }
  }
 
  // If subarray not found
  if (found == false)
  {
    System.out.print("-1");
  }
}
 
// Driver Code
public static void main(String[] args)
{
  // Given array
  int []arr = {20, 34, 51, 10,
               99, 87, 23, 45};
 
  // Given subarray size K
  int K = 3;
 
  // Function Call
  SubarrayHavingPerfectSquare(arr, K);
 
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program for the above approach
from math import sqrt, ceil, floor
 
# Function to check if a given number
# is a perfect square or not
def isPerfectSquare(n):
 
    # Find square root of n
    sr = sqrt(n)
 
    # Check if the square root
    # is an integer or not
    return ((sr - floor(sr)) == 0)
 
# Function to print the subarray
# whose sum is a perfect square
def SubarrayHavingPerfectSquare(arr, k):
 
    ans = [ 0, 0 ]
    sum = 0
 
    # Sum of first K elements
    i = 0
    while i < k:
        sum += arr[i]
        i += 1
 
    found = False
 
    # If the first k elements have
    # a sum as perfect square
    if (isPerfectSquare(sum)):
        ans[0] = 0
        ans[1] = i - 1
 
    else:
 
        # Iterate through the array
        for j in range(i, len(arr)):
            sum = sum + arr[j] - arr[j - k]
 
            # If sum is perfect square
            if (isPerfectSquare(sum)):
                found = True
                ans[0] = j - k + 1
                ans[1] = j
 
        for k in range(ans[0], ans[1] + 1):
            print(arr[k], end = " ")
 
    # If subarray not found
    if (found == False):
        print("-1")
 
# Driver Code
if __name__ == '__main__':
     
    # Given array
    arr = [ 20, 34, 51, 10,
            99, 87, 23, 45 ]
 
    # Given subarray size K
    K = 3
 
    # Function call
    SubarrayHavingPerfectSquare(arr, K)
 
# This code is contributed by mohit kumar 29


C#
// C# program for
// the above approach
using System;
class GFG{
     
class pair
{
  public int first, second;
}
   
// Function to check if a given number
// is a perfect square or not
static bool isPerfectSquare(int n)
{
  // Find square root of n
  double sr = Math.Sqrt(n);
 
  // Check if the square root
  // is an integer or not
  return ((sr - Math.Floor(sr)) == 0);
}
 
// Function to print the subarray
// whose sum is a perfect square
static void SubarrayHavingPerfectSquare(int[] arr,
                                        int k)
{
  pair ans = new pair();
  int sum = 0, i;
 
  // Sum of first K elements
  for (i = 0; i < k; i++)
  {
    sum += arr[i];
  }
 
  bool found = false;
 
  // If the first k elements have
  // a sum as perfect square
  if (isPerfectSquare(sum))
  {
    ans.first = 0;
    ans.second = i - 1;
  }
  else
  {
    // Iterate through the array
    for (int j = i; j < arr.Length; j++)
    {
      sum = sum + arr[j] - arr[j - k];
 
      // If sum is perfect square
      if (isPerfectSquare(sum))
      {
        found = true;
        ans.first = j - k + 1;
        ans.second = j;
      }
    }
 
    for (int k1 = ans.first;
             k1 <= ans.second; k1++)
    {
      Console.Write(arr[k1] + " ");
    }
  }
 
  // If subarray not found
  if (found == false)
  {
    Console.Write("-1");
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given array
  int []arr = {20, 34, 51, 10,
               99, 87, 23, 45};
 
  // Given subarray size K
  int K = 3;
 
  // Function Call
  SubarrayHavingPerfectSquare(arr, K);
 
}
}
 
// This code is contributed by Rajput-Ji


Javascript


输出:
10 99 87

时间复杂度: O(N*log(sum))
辅助空间: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live