给定正整数的数组arr [] ,其中数组的每个元素代表矩形块的长度。任务是找到可以使用矩形块形成的正方形的最大长度。
例子:
Input: arr[] = {3, 2, 1, 5, 2, 4}
Output: 3
Explanation:
Using rectangular block of length 3, 5 and 4, square of side length 3 can be constructed as shown below:
Input: arr[] = {1, 2, 3}
Output: 2
方法:
- 以降序对给定数组进行排序。
- 初始化最大边长(例如maxLength )为0。
- 遍历数组arr [] ,如果arr [i]> maxLength,则增加maxLength并检查此条件以进行下一次迭代。
- 如果上述条件不满足,则中断循环并打印maxLength 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find maximum side
// length of square
void maxSide(int a[], int n)
{
int sideLength = 0;
// Sort array in asc order
sort(a, a + n);
// Traverse array in desc order
for (int i = n - 1; i >= 0; i--) {
if (a[i] > sideLength) {
sideLength++;
}
else {
break;
}
}
cout << sideLength << endl;
}
// Driver Code
int main()
{
int N = 6;
// Given array arr[]
int arr[] = { 3, 2, 1, 5, 2, 4 };
// Function Call
maxSide(arr, N);
return 0;
}
Java
// Java program for the above approach
import java.util.Arrays;
class GFG{
// Function to find maximum side
// length of square
static void maxSide(int a[], int n)
{
int sideLength = 0;
// Sort array in asc order
Arrays.sort(a);
// Traverse array in desc order
for(int i = n - 1; i >= 0; i--)
{
if (a[i] > sideLength)
{
sideLength++;
}
else
{
break;
}
}
System.out.println(sideLength);
}
// Driver code
public static void main (String[] args)
{
int N = 6;
// Given array arr[]
int arr[] = new int[]{ 3, 2, 1,
5, 2, 4 };
// Function Call
maxSide(arr, N);
}
}
// This code is contributed by Pratima Pandey
Python3
# Python3 program for the above approach
# Function to find maximum side
# length of square
def maxSide(a, n):
sideLength = 0
# Sort array in asc order
a.sort
# Traverse array in desc order
for i in range(n - 1, -1, -1):
if (a[i] > sideLength):
sideLength += 1
else:
break
print(sideLength)
# Driver code
N = 6
# Given array arr[]
arr = [ 3, 2, 1, 5, 2, 4 ]
# Function Call
maxSide(arr, N)
# This code is contributed by divyeshrabadiya07
C#
// C# program for the above approach
using System;
class GFG{
// Function to find maximum side
// length of square
static void maxSide(int []a, int n)
{
int sideLength = 0;
// Sort array in asc order
Array.Sort(a);
// Traverse array in desc order
for(int i = n - 1; i >= 0; i--)
{
if (a[i] > sideLength)
{
sideLength++;
}
else
{
break;
}
}
Console.Write(sideLength);
}
// Driver code
public static void Main()
{
int N = 6;
// Given array arr[]
int []arr = new int[]{ 3, 2, 1,
5, 2, 4 };
// Function Call
maxSide(arr, N);
}
}
// This code is contributed by Code_Mech
Javascript
输出:
3
时间复杂度: O(N * log N)
辅助空间: O(1)