C语言数据结构-顺序表删除指定范围V2.0

顺序表删除指定范围

顺序表 删除指定范围

设计一个高效的算法,从顺序表L中删除所有值介于x和y之间(包括x和y)的所有元素(假设y>=x),要求时间复杂度为O(n),空间复杂度为O(1)。

函数原型如下:
void del_x2y(SeqList *L, ElemType x, ElemType y);

相关定义如下:

struct _seqlist{
    ElemType elem[MAXSIZE];
    int last;
};
typedef struct _seqlist SeqList;

提供代码

#include <stdio.h>
#include <stdlib.h>
#include "list.h" // 请不要删除,否则检查不通过

void del_x2y(SeqList *L, ElemType x, ElemType y) {

}

 参考代码v2.0.0改为赋值而非顺序表的删除只使用一个循环,符合要求

/*
顺序表 删除指定范围
设计一个高效的算法,从顺序表L中删除所有值介于x和y之间(包括x和y)的所有元素(假设y>=x),
要求时间复杂度为O(n),空间复杂度为O(1)。
函数原型如下:
void del_x2y(SeqList *L, ElemType x, ElemType y);
相关定义如下:
struct _seqlist{
    ElemType elem[MAXSIZE];//静态数组
    int last;//存放最后一个元素的下标
};
typedef struct _seqlist SeqList;
*/

/*
V2.0 时间复杂度为O(n)
要求只能存在一个循环
*/

#include <stdio.h>
#include <stdlib.h>
//#include "list.h" // 请不要删除,否则检查不通过

#define ElemType int
#define MAXSIZE 10

struct _seqlist {
    ElemType elem[MAXSIZE];
    int last;
};
typedef struct _seqlist SeqList;


void del_x2y(SeqList* L, ElemType x, ElemType y) 
{
    int i = 0, j = 0;
    for (i = 0; i <= L->last; i++) {
        if (L->elem[i] < x || L->elem[i] > y) {
            L->elem[j++] = L->elem[i]; //在范围外,则继续赋值
        }
    }
    L->last = j-1;//储存下标位置
}

void print(const SeqList* L)
{
    int i = 0;
    for (i = 0; i <= L->last; i++)
    {
        printf("%d ",L->elem[i]);
    }
}


int main()
{
    SeqList L = { {0,1,2,3,4,5,6,7,8,9},8 };//测试用例0 1 2 6 7 8
    del_x2y(&L,3,5);
    print(&L);//打印看是否删除成功
    return 0;
}

参考代码v1.0.0复杂度过高,不符合要求

/*
题目分析:时间复杂度为O(n),空间复杂度为O(1)
则要求遍历数组,并且只能有一个临时变量
*/

#include <stdio.h>
#include <stdlib.h>
//#include "list.h" // 请不要删除,否则检查不通过

#define ElemType int
#define MAXSIZE 10

struct _seqlist {
    ElemType elem[MAXSIZE];
    int last;
};
typedef struct _seqlist SeqList;


void del_x2y(SeqList* L, ElemType x, ElemType y) 
{
    int i = 0;
    while (i<=L->last)
    {  
        int j = 0;
        //SeqList* tmp = L;
        //判断元素是不是在这个范围内
        if ((L->elem[i] >= x) && (L->elem[i] <= y))
        {
            //删除元素=将后面的都将前移动一位,并且last--
            for (j = i; j < L->last; j++)
            {
                L->elem[j] = L->elem[j + 1];
            }
            L->last--;
        }
        else
        {
            i++;
        }     
    }
    
}

void print(const SeqList* L)
{
    int i = 0;
    for (i = 0; i <= L->last; i++)
    {
        printf("%d ",L->elem[i]);
    }
}


int main()
{
    SeqList L = { {0,1,2,3,4,5,6,7,8,9},8 };//测试用例
    del_x2y(&L,3,5);
    print(&L);//打印看是否删除成功
    return 0;
}
  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值