📜  检查给定范围内的子数组的总和是否为完美平方

📅  最后修改于: 2021-04-23 15:55:15             🧑  作者: Mango

给定大小为N的数组arr []范围为range []的数组,任务是检查子数组{range [0],..,range [1]}的和是否为完美平方。如果总和是理想平方,则打印总和的平方根。否则,打印-1。

例子 :

天真的方法:最简单的方法是遍历子数组,并检查子数组的和是否为完美平方。

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

高效方法:为了优化上述方法,其思想是使用二进制搜索来计算子数组总和的平方根。请按照以下步骤操作:

  1. 计算给定range []中子数组的总和。
  2. 现在,使用二进制搜索在0和范围内求和的平方根。
  3. 从起始值和最后一个值中查找中值元素,然后将中值2的值与总和进行比较
  4. 如果值 中点2等于总和,找到一个完美的平方,然后返回中点。
  5. 如果mid 2的值大于总和,则答案只能位于mid元素之后的范围的右侧。因此,请重新找回正确的位置,并将搜索空间减小到01之间
  6. 如果mid 2的值小于总和,请将搜索空间减小到mid +1以求和。

下面是上述方法的实现。

C++
// C++ implementation of
// the above approach
#include 
using namespace std;
 
// Function to calculate the square
// root of the sum of a subarray in
// a given range
int checkForPerfectSquare(vector arr,
                          int i, int j)
{
    int mid, sum = 0;
 
    // Calculate the sum of array
    // elements within a given range
    for (int m = i; m <= j; m++) {
        sum += arr[m];
    }
 
    // Finding the square root
    int low = 0, high = sum / 2;
    while (low <= high) {
        mid = low + (high - low) / 2;
 
        // If a perfect square is found
        if (mid * mid == sum) {
            return mid;
        }
 
        // Reduce the search space if
        // the value is greater than sum
        else if (mid * mid > sum) {
            high = mid - 1;
        }
 
        // Reduce the search space if
        // the value if smaller than sum
        else {
            low = mid + 1;
        }
    }
    return -1;
}
 
// Driver Code
int main()
{
    // Given Array
    vector arr;
    arr = { 2, 19, 33, 48, 90, 100 };
 
    // Given range
    int L = 1, R = 3;
 
    // Function Call
    cout << checkForPerfectSquare(arr, L, R);
    return 0;
}


Java
// Java implementation of
// the above approach
import java.util.*;
class GFG{
 
// Function to calculate the square
// root of the sum of a subarray in
// a given range
static int checkForPerfectSquare(int []arr,
                                 int i, int j)
{
  int mid, sum = 0;
 
  // Calculate the sum of array
  // elements within a given range
  for (int m = i; m <= j; m++)
  {
    sum += arr[m];
  }
 
  // Finding the square root
  int low = 0, high = sum / 2;
  while (low <= high)
  {
    mid = low + (high - low) / 2;
 
    // If a perfect square
    // is found
    if (mid * mid == sum)
    {
      return mid;
    }
 
    // Reduce the search space
    // if the value is greater
    // than sum
    else if (mid * mid > sum)
    {
      high = mid - 1;
    }
 
    // Reduce the search space
    // if the value if smaller
    // than sum
    else
    {
      low = mid + 1;
    }
  }
  return -1;
}
 
// Driver Code
public static void main(String[] args)
{
  // Given Array
  int []arr = {2, 19, 33,
               48, 90, 100};
 
  // Given range
  int L = 1, R = 3;
 
  // Function Call
  System.out.print(
         checkForPerfectSquare(arr, L, R));
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 implementation of
# the above approach
 
# Function to calculate the square
# root of the sum of a subarray in
# a given range
def checkForPerfectSquare(arr, i, j):
 
    mid, sum = 0, 0
 
    # Calculate the sum of array
    # elements within a given range
    for m in range(i, j + 1):
        sum += arr[m]
 
    # Finding the square root
    low = 0
    high = sum // 2
     
    while (low <= high):
        mid = low + (high - low) // 2
 
        # If a perfect square is found
        if (mid * mid == sum):
            return mid
 
        # Reduce the search space if
        # the value is greater than sum
        elif (mid * mid > sum):
            high = mid - 1
 
        # Reduce the search space if
        # the value if smaller than sum
        else:
            low = mid + 1
 
    return -1
 
# Driver Code
if __name__ == '__main__':
 
    # Given Array
    arr = [ 2, 19, 33, 48, 90, 100 ]
 
    # Given range
    L = 1
    R = 3
 
    # Function call
    print(checkForPerfectSquare(arr, L, R))
 
# This code is contributed by mohit kumar 29


C#
// C# implementation of
// the above approach
using System;
class GFG{
 
// Function to calculate the square
// root of the sum of a subarray in
// a given range
static int checkForPerfectSquare(int []arr,
                                 int i, int j)
{
  int mid, sum = 0;
 
  // Calculate the sum of array
  // elements within a given range
  for (int m = i; m <= j; m++)
  {
    sum += arr[m];
  }
 
  // Finding the square root
  int low = 0, high = sum / 2;
  while (low <= high)
  {
    mid = low + (high - low) / 2;
 
    // If a perfect square
    // is found
    if (mid * mid == sum)
    {
      return mid;
    }
 
    // Reduce the search space
    // if the value is greater
    // than sum
    else if (mid * mid > sum)
    {
      high = mid - 1;
    }
 
    // Reduce the search space
    // if the value if smaller
    // than sum
    else
    {
      low = mid + 1;
    }
  }
  return -1;
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given Array
  int []arr = {2, 19, 33,
               48, 90, 100};
 
  // Given range
  int L = 1, R = 3;
 
  // Function Call
  Console.Write(checkForPerfectSquare(arr,
                                      L, R));}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
10

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