当前位置:网站首页>C语言一维数组练习——将m个元素移动到数组尾部
C语言一维数组练习——将m个元素移动到数组尾部
2022-08-02 14:02:00 【iccoke】
将m个元素放到数组尾部
这里我们的思路是将数组的前m个元素存储到另一个数组后然后再将剩余元素往前移动m位,然后再将存储的元素加到数组的尾部即可
具体代码
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<assert.h>
void moveelement(int *arr,int *brr,int m,int len) {
int i = 0; int j = 0;
int k = 0;
assert(m < len);
for ( i = 0; i < m; i++) {
brr[i] = arr[i];
}
for ( j = m; j < len; j++) {
arr[j - m] = arr[j];
}
for (int n = len - m; n < len; n++) {
arr[n] = brr[k];
k++;
}
return;
}
int main() {
int arr[] = { 1,2,3,4,5,6 };
int brr[10];
int m = 2;
int len = sizeof(arr) / sizeof(arr[0]);
moveelement(arr, brr, m, len);
for (int w = 0; w < len; w++) {
printf("% d", arr[w]);
}
}将前两个元素移动到尾部

但是这个代码开辟了新的内存空间,所以这个代码的空间复杂度又比较大,因此我们需要进行优化
我们可以采取另外一种思路
关于时间复杂度和空间复杂度
算法的时间复杂度与空间复杂度_iccoke的博客-CSDN博客
将整个数组扭转,再根据要求再扭转
例如
将 1,2,3,4,5,6的前2位移动到尾部
先全部扭转,结果为
6,5,4,3,2,1
再分别扭转前四个和后两个即可
扭转前四个结果为
3,4,5,6,2,1
最后扭转后两位结果为
3,4,5,6,1,2
这样就以一种比较低的空间复杂度完成了我们的目的
具体代码如下
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<assert.h>
void Reverse(int* arr, int begin, int end) {
assert(arr != NULL && end >= begin);
int temp;
int n = (end - begin + 1) / 2;
for (int i = 0; i < n; i++,begin++,end--) {
temp=arr[end];
arr[end] = arr[begin];
arr[begin] = temp;
}
}
void moveelement(int* arr, int len, int m) {
assert(arr != NULL);
Reverse(arr, 0, len - 1);
Reverse(arr, 0, len - m - 1);
Reverse(arr, len - m, len - 1);
}
int main() {
int arr[] = { 1,2,3,4,5,6 };
int len = sizeof(arr) / sizeof(arr[0]);
moveelement(arr, len, 2);
for (int i = 0; i < len ; i++) {
printf("%5d", arr[i]);
}
return 0;
}结果如下

边栏推荐
猜你喜欢
![[ROS] (01) Create ROS workspace](/img/2a/11e5023ef6d052d98b4090d2eea017.png)
[ROS] (01) Create ROS workspace

Visual Studio配置OpenCV之后,提示:#include<opencv2/opencv.hpp>无法打开源文件

c语言三子棋详解!!! (电脑智能下棋)(附上完整代码)

猜数字游戏,猜错10次关机(srand、rand、time)随机数生成三板斧(详细讲解!不懂问我!)

8581 线性链表逆置

使用云GPU+pycharm训练模型实现后台跑程序、自动保存训练结果、服务器自动关机

Unit 13 Mixing in View Base Classes

static关键字3种作用,简单粗暴对比,好理解
ROS通信 —— 节点,Nodes & Master](/img/f5/c541259b69a0db3dc15a61e87f0415.png)
[ROS](05)ROS通信 —— 节点,Nodes & Master

跑yolov5又出啥问题了(1)p,r,map全部为0
随机推荐
MySQL数据库语法格式
8576 Basic operations of sequential linear tables
Tornado框架路由系统介绍及(IOloop.current().start())启动源码分析
Unit 5 Hold Status
Basic operations of 8583 sequential stack
Flask framework in-depth
8581 Linear linked list inversion
Unit 8 Middleware
verilog学习|《Verilog数字系统设计教程》夏宇闻 第三版思考题答案(第七章)
paddleocr window10初体验
第十单元 前后连调
ToF相机从Camera2 API中获取DEPTH16格式深度图
redis延时队列
Hands-on OCR (1)
8580 Merge linked list
The specific operation process of cloud GPU (Hengyuan cloud) training
[ROS] Introduction to common tools in ROS (to be continued)
Flask framework
[ROS] The software package of the industrial computer does not compile
Verilog学习 系列