当前位置:网站首页>在数组中指定位置插入任意一个元素及删除数组中值为x的元素
在数组中指定位置插入任意一个元素及删除数组中值为x的元素
2022-07-15 16:56:00 【Smile Hun】
在数组中指定位置插入任意一个元素
思路
通过后移鼠标指针完成对数组的加长以及对目标位置之后的值完成复制和移动,腾出目标位置的空间来存放需要插入的值
#include<stdio.h>
#include<assert.h>
void insert(int a[], int pos, int x,int length);
int main()
{
int a[10] = {
1,2,3,4,5 };
int x, pos = 0, length = 10;
scanf_s("%d %d", &x, &pos);
insert(a,pos,x,length);
length++;
for (int i = 0; i < length;i++ ) {
printf("%d", a[i]);
}
printf("\n%d", length);
}
void insert(int a[], int pos, int x,int length) {
/*在第pos个元素插入x值*/
assert(length < 10);//assert()如果它的条件返回错误,则终止程序执行
for (int i = length; i >= pos; i--) {
a[i] = a[i-1];
}
a[pos-1] = x;
}
assert()函数
- 使用方法
导入<assert.h>库函数
assert( 表达式 ) 例:assert(a<10) - 作用
判断括号内语句是否成立,若成立则继续执行,若不成立则终值程序执行并报错
assert()函数详解
删除数组中所有值为x的元素
#include<stdio.h>
void delete_n(int a[], int x, int& length);
void remove_a_num(int a[], int i, int length);
int main()
{
int a[10] = {
1,2,3,3,5,2,5,3,3,4 };
int x, length = 10;
scanf_s("%d", &x);
delete_n(a, x, length);
for (int i = 0; i < length; i++) {
printf("%d", a[i]);
}
printf("\n%d", length);
}
void delete_n(int a[], int x, int& length) {
int i = 0;
while (i < length) {
if (a[i] == x) {
remove_a_num(a, i, length);
length--;
}
else {
i++;
}
}
}
void remove_a_num(int a[], int i, int length) {
while (i < length) {
a[i] = a[i + 1];
i++;
}
}
删除数组中所有值为x的元素 方法改良
#include <stdio.h>
int main() {
int a[10] = {
2,3,1,3,3,5,6,4,3,2 };
int m = 0;
int len = 10;
int x;
for (int i = 0; i < len; i++) {
printf("%d ", a[i]);
}
printf("\n");
scanf_s("%d", &x);
printf("\n");
for (int i = 0; i < len; i++) {
if (a[i] == x) {
m++;
}
else
{
a[i - m] = a[i];
}
}
for (int i = 0; i < len-m; i++) {
printf("%d ", a[i]);
}
}
时间复杂度从n²降到了n,可以提高效率
边栏推荐
- Preliminary introduction of CAN protocol
- GridSearchCV报错:ValueError: Input contains NaN, infinity or a value too large for dtype(‘float64‘).
- H264编码器的一种率失真优化(1)
- C language Chapter 9 string
- [problems of dft/fft - solutions to fence effect]
- Design and implementation of fingertip Roulette Games (uniapp implements wechat applet)
- Lifecycle: the foundation of lifecycle aware components - jetpack series (1)
- RuntimeWarning: overflow encountered in long_ scalars h = 12.0 / (totaln * (totaln + 1)) * ssbn - 3
- Tips for setting dropout parameters
- Rhcsa note 2
猜你喜欢
随机推荐
Ffmpeg sample analysis: muting c
[interview must brush 101] hash
Domestic light! High score spatiotemporal representation learning model uniformer
通达信开户选哪个证券公司 开户安全吗?
C语言 第九章 字符串
Type-C charging OTG chip (ldr6028s)
唐门暗器之私有云排名
(1) Matlab Basics
产品-Axure9英文版,使用Repeater中继器实现下拉多选框
Oscilloscope use concept record
[interview brush 101] double pointer
Sensor principle article
TP5 分页一些小点
FFmpeg sample 分析:muxing.c
flowable 流程自定义属性
保留小数位数时,可能会出现不按四舍五入进位,简单的解决方案
Thumbnail image processing class library
MySQL index
Redis介绍和安装
The IP address of the database is stored. What data type is used









