移除元素(友好版)

盛夏的中午真的好热😢

大家好,这里是甜瓜一号✨

今天小小的水一下,带来一道比较简单的题目😊(大佬可以略过了哈哈哈)

🍓问题详情

给你一个数组 nums 和一个值 val,你需要移除所有数值等于 val 的元素,并返回移除后数组的新长度。移除元素后数组里的元素可以不按顺序出现。

🍓数据结构与算法

数组+链表

  1. 数组使用的是双指针的形式
  2. 链表采用断开的方式

🍓代码详情

package 移除元素;

public class ch01 {
    public static class Node{
        int n;
        Node next;

        public Node(int n){
            this.n=n;
        }

        public Node(){}

    }
    public void remove(int[] array,int value){
        ch01.Node head=new ch01.Node();
        ch01.Node p=head;
        int a=0;
        for(int i=0;i<array.length;i++){
            if(array[i]!=value) {
                ch01.Node node = new ch01.Node(array[i]);
                head.next = node;
                head = head.next;
                a++;
            }
        }
        System.out.println("移除元素后的数组大小:"+a);
        System.out.println("移除元素后的数组元素为:");
        for(int i=0;i<a;i++){
            p=p.next;
            System.out.print(p.n+" ");
        }
    }
}
package 移除元素;

public class ch02 {
    public void remove(int[] arr,int val){
        int left=0;
        int right=arr.length;
        while(left<right){
            if(arr[left]==val){
                arr[left]=arr[right-1];
                right--;
            }else{
                left++;
            }
        }
        System.out.println("移除元素后的数组大小:"+left);
        System.out.println("移除元素后的数组元素为:");
        for(int i=0;i<left;i++){
            System.out.print(arr[i]+" ");
        }
    }

}
package 移除元素;

import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        System.out.println("请输入数组个数:");
        Scanner sc=new Scanner(System.in);
        int m=sc.nextInt();
        int[] arr=new int[m];
        System.out.println("请输入数组元素:");
        for(int i=0;i<m;i++){
            arr[i]=sc.nextInt();
        }
        System.out.println("请输入要去除的元素:");
        int n=sc.nextInt();
        ch01 c=new ch01();
        c.remove(arr,n);
        System.out.println();
        ch02 c2=new ch02();
        c2.remove(arr,n);
    }
}

🍓注意事项

在链表法中,注意一开始的right=arr.length;

如果一开始的right=arr.length-1,则在最后要注意加上left==right的情况,为了防止最后的left和right同时指向的那个值符合情况却不能展示出来。

//添加情况如下所示
if(left==right&&arr[left]!=val){
            left++;
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值