使用C++编写的数组旋转的逆转算法

2023年 8月 29日 30.9k 0

使用C++编写的数组旋转的逆转算法

在给定的问题中,我们有一个数组,并且我们需要使用反转算法将数组旋转d个元素,例如 −

Input : arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2
Output : arr[] = [3, 4, 5, 6, 7, 1, 2]
Explanation : As you can see we have to rotate this array by d = 2 but our main task is to achieve this by using a reversal technique.

登录后复制

我们对数组的旋转进行了一些反转技术的计算,并得出结论:

  • 首先,我们反转数组的前d个元素。
  • 其次,我们反转剩下的元素。
  • 第三,我们反转整个数组。

通过应用这三个步骤,我们可以得到旋转后的数组。

解决方案的方法

在这个问题中,首先,我们要编写一个反转元素的函数;现在我们按照上述步骤进行操作。

示例

#include
using namespace std;

void reverseArray(int arr[], int start, int end) { // our reversal algorithm
while (start < end) { // if start becomes equal to end we break the loop
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
return ;
}
void Rotate(int arr[], int d, int n) { // rotation function
if (d == 0) // no rotation required
return;
d = d % n; // when d becomes equal to n so our array comes to its original form
reverseArray(arr, 0, d - 1); // reversing first d elements
reverseArray(arr, d, n - 1); // reversing the remaining elements
reverseArray(arr, 0, n - 1); // reversing the whole array

return ;
}
int main() {
int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; // given array
int n = sizeof(arr) / sizeof(arr[0]); // size of our array
int d = 2;
Rotate(arr, d, n);
for(int i = 0; i < n; i++) // printing the array
cout

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论