打印 旋转数组_C ++程序打印数组的左旋转

打印 旋转数组

Problem statement:

问题陈述:

Given an array of N elements and the task is to print the elements of an array after left rotating array elements by d positions.

给定一个由N个元素组成的数组,任务是在将数组元素左旋转 d个位置后打印该数组的元素

Input: N, d and next line containing the n elements of array.

输入: N , d和包含数组n个元素的下一行。

Output: Array elements after d rotation.

输出: d旋转后的数组元素。

Example:

例:

    Input:
    n = 7, d = 2
    array elements: 1 2 3 4 5 6 7

    Output: 
    3 4 5 6 7 1 2

Solution:

解:

The naïve approach to solve this problem is to shift the all elements d times but this is a time-consuming process.

解决此问题的幼稚方法是将所有元素移动d次,但这是一个耗时的过程。

We can use a small trick here to print the elements of the array after left rotating d elements.

我们可以在此处使用一个小技巧,在向左旋转d个元素后打印该数组的元素。

    Let,
    i = ith iteration
    D = number of elements to rotate
    N = size of array
    Then to left rotate array we can use -
    arr[i] = arr[(i+D)%N]

C++ Implementation:

C ++实现:

#include <iostream>
using namespace std;

int main()
{
	int n,d;

	//input value of n and d
	cout<<"Enter the value of n and d"<<endl;
	cin>>n>>d;
	int a[n];

	//input array elements
	cout<<"enter the array elements : ";
	for(int i=0;i<n;i++)
	{
		cin>>a[i];
	}

	//print the elements of array after rotation
	cout<<"array elements after rotation : ";
	for(int i=0;i<n;i++)
	{
		cout<<a[(i+d)%n]<<" ";
	}

	return 0;
}

Output

输出量

Enter the value of n and d
7 3
enter the array elements : 1 2 3 4 5 6 7
array elements after rotation : 4 5 6 7 1 2 3


翻译自: https://www.includehelp.com/cpp-programs/print-the-left-rotation-of-the-array.aspx

打印 旋转数组

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值