给定数组arr []和数组中的位置k。编写一个函数名称reverse(a [],k),以使其反转子数组arr [0..k-1]。使用的额外空间应为O(1),时间复杂度应为O(k)。
例子:
Input:
arr[] = {1, 2, 3, 4, 5, 6}
k = 4
Output:
arr[] = {4, 3, 2, 1, 5, 6}
强烈建议您最小化浏览器,然后自己尝试。
下面是相同的实现。
C++
// C++ program to reverse a subarray arr[0..k-1]
#include
using namespace std;
// Reverse subarray a[0..k-1]
void reverse(int a[], int n, int k)
{
if (k > n)
{
cout << "Invalid k";
return;
}
// One by one reverse first and last elements of a[0..k-1]
for (int i = 0; i < k/2; i++)
swap(a[i], a[k-i-1]);
}
// Driver program
int main()
{
int a[] = {1, 2, 3, 4, 5, 6};
int n = sizeof(a) / sizeof(int), k = 4;
reverse(a, n, k);
for (int i = 0; i < n; ++i)
printf("%d ", a[i]);
return 0;
}
Java
// java program to reverse a
// subarray arr[0..k-1]
public class GFG {
// Reverse subarray a[0..k-1]
static void reverse(int []a, int n, int k)
{
if (k > n)
{
System.out.println( "Invalid k");
return;
}
// One by one reverse first
// and last elements of a[0..k-1]
for (int i = 0; i < k / 2; i++)
{
int tempswap = a[i];
a[i] = a[k - i - 1];
a[k - i - 1] = tempswap;
}
}
// Driver code
public static void main(String args[])
{
int []a = {1, 2, 3, 4, 5, 6};
int n = a.length, k = 4;
reverse(a, n, k);
for (int i = 0; i < n; ++i)
System.out.print(a[i] + " ");
}
}
// This code is contributed by Sam007.
Python3
# python program to reverse a subarray
# arr[0..k-1]
from __future__ import print_function
# Reverse subarray a[0..k-1]
def reverse(a, n, k):
if (k > n):
print( "Invalid k")
return
# One by one reverse first and
# last elements of a[0..k-1]
for i in range(0, (int)(k/2)):
temp = a[i]
a[i] = a[k-i-1]
a[k-i-1] = temp
# Driver program
a = [1, 2, 3, 4, 5, 6]
n = len(a)
k = 4
reverse(a, n, k);
for i in range(0, n):
print(a[i], end=" ")
# This code is contributed by Sam007.
C#
// C# program to reverse a
// subarray arr[0..k-1]
using System;
class GFG {
static void SwapNum(ref int x, ref int y)
{
int tempswap = x;
x = y;
y = tempswap;
}
// Reverse subarray a[0..k-1]
static void reverse(int []a, int n,
int k)
{
if (k > n)
{
Console.Write( "Invalid k");
return;
}
// One by one reverse first
// and last elements of a[0..k-1]
for (int i = 0; i < k / 2; i++)
SwapNum(ref a[i], ref a[k - i - 1]);
}
// Driver Code
public static void Main()
{
int []a = {1, 2, 3, 4, 5, 6};
int n = a.Length, k = 4;
reverse(a, n, k);
for (int i = 0; i < n; ++i)
Console.Write(a[i] + " ");
}
}
// This code is contributed by Sam007
Javascript
输出:
4 3 2 1 5 6
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。