盛夏的中午真的好热😢
大家好,这里是甜瓜一号✨
今天小小的水一下,带来一道比较简单的题目😊(大佬可以略过了哈哈哈)
🍓问题详情
给你一个数组
nums
和一个值val
,你需要移除所有数值等于val
的元素,并返回移除后数组的新长度。移除元素后数组里的元素可以不按顺序出现。
🍓数据结构与算法
数组+链表
- 数组使用的是双指针的形式
- 链表采用断开的方式
🍓代码详情
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++;
}