给定一个由[0, 9]范围内的N 个整数组成的数组arr[] ,任务是找到一个长度为K的子数组,我们可以从中生成一个数字,即回文数。如果不存在这样的子数组,则打印-1 。
注意:数组中的元素在 0 到 10 的范围内。
例子:
Input: arr[] = {1, 5, 3, 2, 3, 5, 4}, K = 5
Output: 5, 3, 2, 3, 5
Explanation:
Number generated by concatenating all elements of the subarray, i.e. 53235, is a palindrome.
Input: arr[] = {2, 3, 5, 1, 3}, K = 4
Output: -1
朴素方法:解决问题的最简单方法是生成长度为K 的所有子数组,并为每个子数组连接子数组中的所有元素并检查形成的数字是否为回文数。
时间复杂度: O(N 3 )
辅助空间: O(K)
有效方法:可以使用Window-Sliding 技术解决该问题。请按照以下步骤解决问题:
- 做一个回文函数来检查给定的子数组(Window-Sliding)是否是回文。
- 遍历数组,并为每个子数组调用回文函数。
- 如果发现为真,则返回该子数组的起始索引,并打印从起始索引到下一个 k 索引的数组。
- 如果找不到这样的回文子数组,则打印 -1。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check if a number
// is Palindrome or not
// here i is the starting index
// and j is the last index of the subarray
bool palindrome(vector a, int i, int j)
{
while(i arr, int k)
{
int n= sizeof(arr)/sizeof(arr[0]);
// Iterating over subarray of length k
// and checking if that subarray is palindrome
for(int i=0; i<=n-k; i++){
if(palindrome(arr, i, i+k-1))
return i;
}
// If no subarray is palindrome
return -1;
}
// Driver Code
int main()
{
vector arr = { 2, 3, 5, 1, 3 };
int k = 4;
int ans = findSubArray(arr, k);
if (ans == -1)
cout << -1 << "\n";
else {
for (int i = ans; i < ans + k;
i++)
cout << arr[i] << " ";
cout << "\n";
}
return 0;
}
// This code is contributed by Prafulla Shekhar
Java
// Java program for the above approach
import java.io.*;
class GFG
{
// Function to check if a number
// is Palindrome or not
// here i is the starting index
// and j is the last index of the subarray
public static boolean palindrome(int[] a, int i, int j)
{
while(i
C#
// C# program for the above approach
using System;
class GFG{
// Function to check if a number
// is Palindrome or not here i is
// the starting index and j is the
// last index of the subarray
public static bool palindrome(int[] a, int i,
int j)
{
while (i < j)
{
// If the integer at i is not equal to j
// then the subarray is not palindrome
if (a[i] != a[j])
return false;
// Otherwise
i++;
j--;
}
// All a[i] is equal to a[j]
// then the subarray is palindrome
return true;
}
// Function to find a subarray whose
// concatenation forms a palindrome
// and return its starting index
static int findSubArray(int[] arr, int k)
{
int n = arr.Length;
// Iterating over subarray of length k
// and checking if that subarray is palindrome
for(int i = 0; i <= n - k; i++)
{
if (palindrome(arr, i, i + k - 1))
return i;
}
// If no subarray is palindrome
return -1;
}
// Driver code
public static void Main(String[] args)
{
int[] arr = { 2, 3, 5, 1, 3 };
int k = 4;
int ans = findSubArray(arr, k);
if (ans == -1)
Console.Write(-1 + "\n");
else
{
for(int i = ans; i < ans + k; i++)
Console.Write(arr[i] + " ");
Console.Write("\n");
}
}
}
// This code is contributed by aashish1995
Javascript
输出
-1
时间复杂度: O(N)
辅助空间: O(1)