数据结构(Java)之数组(4)-包含,搜索和删除功能的实现

包含:
查找数组中是否有元素e
思路:
①遍历数组中的元素
②逐一判断是否有元素=e,若找到返回true
③遍历结束还没找到,返回false

//查找数组中是否有元素e
    public boolean contains(int e){
        for (int i = 0; i < size; i++) {
            if (data[i] == e){
                return true;
            }
        }
        return false;
    }

搜索:
查找数组中元素e所在的索引,如果不存在元素e,则返回-1
思路:
①遍历数组中的元素
②逐一判断是否有元素=e,若找到返回该元素的索引i
③遍历结束还没找到,返回-1

//查找数组中元素e所在的索引,如果不存在元素e,则返回-1
    public int find(int e){
        for (int i = 0; i < size; i++) {
            if (data[i] == e){
                return i;
            }
        }
        return -1;
    }

删除:
从数组中删除指定位置的元素
思路:
①判断传入的index是否合法 >0 <=size
②将index位置后的元素依次向前移动
③size–

//从数组中删除index位置的元素,返回删除的元素
    public int remove(int index){
        if (index<0|| index>=size){
            throw new IllegalArgumentException("Get failed.Index is illega");
        }
        int ret = data[index];
        for (int i = index; i < size; i++) {
            data[i]  = data[i+1];
        }
        size--;
        return ret;
    }
   //从数组中删除第一个元素,返回删除的元素
    public int removeFirst(){
        return remove(0);
    }
    //从数组中删除最后一个元素,返回删除的元素
    public int removeLast(){
        return remove(size-1);
    }

从数组中删除元素e

//从数组中删除元素e
    public void removeElement(int e){
        int index = find(e);
        if (index != -1){
            remove(index);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值