昨日去某公司笔试,碰到一个题如下:
对于一个数组,已知其长度为n,和一小于n的正整数p,将该数组的前p个元素和后面的元素交换一下位置,例如a[15]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,2,3,4,5,6},若p=6,则输出为{7,8,9,10,11,12,13,14,15},
要求占用尽可能少的空间。
思路:其实方法很简单,将每一个元素都向前移动一位,移动P次即可,不要陷入怎么分段拷贝的思路中。
1
#include
<
iostream.h
>
2
3 void move( int * s, int m, int n);
4
5 void main()
6 {
7 int p;
8 int arr[ 15 ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 };
9 cout << " the orignal array data is: " << endl;
10 for ( int i = 0 ;i < 15 ;i ++ )
11 cout << arr[i] << " " ;
12 cout << endl;
13
14 cout << " please input a integer: " ;
15 cin >> p;
16
17 move(arr,p, sizeof (arr) / sizeof (arr[ 0 ]));
18
19 cout << " the output arry is: " << endl;
20 for (i = 0 ;i < 15 ;i ++ )
21 cout << arr[i] << " " ;
22 cout << endl;
23 }
24
25 void move( int * s, int m, int n)
26 {
27 for ( int i = 0 ;i < m;i ++ )
28 {
29 int temp = s[ 0 ];
30 for ( int j = 0 ;j < n - 1 ;j ++ )
31 s[j] = s[j + 1 ];
32 s[n - 1 ] = temp;
33
34 }
35
36 }
2
3 void move( int * s, int m, int n);
4
5 void main()
6 {
7 int p;
8 int arr[ 15 ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 };
9 cout << " the orignal array data is: " << endl;
10 for ( int i = 0 ;i < 15 ;i ++ )
11 cout << arr[i] << " " ;
12 cout << endl;
13
14 cout << " please input a integer: " ;
15 cin >> p;
16
17 move(arr,p, sizeof (arr) / sizeof (arr[ 0 ]));
18
19 cout << " the output arry is: " << endl;
20 for (i = 0 ;i < 15 ;i ++ )
21 cout << arr[i] << " " ;
22 cout << endl;
23 }
24
25 void move( int * s, int m, int n)
26 {
27 for ( int i = 0 ;i < m;i ++ )
28 {
29 int temp = s[ 0 ];
30 for ( int j = 0 ;j < n - 1 ;j ++ )
31 s[j] = s[j + 1 ];
32 s[n - 1 ] = temp;
33
34 }
35
36 }