C++ 数组元素循环右移问题

 这道题要求不用另外的数组,并且尽量移动次数少。

算法思想:设计一个结构体存储数组数据和它应在的索引位置,再直接交换,但是这种方法不能一次性就移动完成,因此再加一个判断条件。等这个判断条件满足后就退出循环。

 

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <vector>
 4 
 5 using namespace std;
 6 
 7 struct Num_struct
 8 {
 9     int data;
10     int should_index;
11 };
12 
13 bool is_complete(vector<Num_struct> &arr ,int length)
14 {
15     bool flag = true;
16     for(int i = 0;i < length;++i)
17     {
18         if(arr[i].should_index != i)
19         {
20             flag = false;
21         }
22     }
23     return flag;
24 }
25 
26 int main()
27 {
28     int length = 0;
29     int moves = 0;
30     cin >> length >> moves;
31     moves %= length;
32 
33     vector<Num_struct> arr;
34     arr.reserve(length);
35     for(int i = 0;i < length;++i)
36     {
37         Num_struct num;
38         cin >> num.data;
39         int index = (i + moves)%length;
40         num.should_index = index;
41         arr[i] = num;
42     }
43 
44     if(moves != 0)
45     {
46         while(!is_complete(arr,length))
47         {
48             for(int i = 0;i < length;++i)
49             {
50                 int index = arr[i].should_index;
51                 swap(arr[i],arr[index]);
52             }
53         }
54     }
55 
56     for(int i = 0;i < length;++i)
57     {
58         cout << arr[i].data;
59         if(i != length-1)
60         {
61             cout << " ";
62         }
63     }
64 
65     return 0;
66 }

 

posted on 2020-04-20 16:30  秃头女孩今夜也不睡觉  阅读(903)  评论(0编辑  收藏  举报

导航