删除数组的头部元素,尾部元素,数组中的特定值
例如,数组{1,2,3,3,6,4,5,6,6,6,6},删除头部元素,结果:{2,3,3,6,4,5,6,6,6,6}
数组{1,2,3,3,6,4,5,6,6,6,6},删除尾部元素,结果:{1,2,3,3,6,4,5,6,6,6}
数组{1,2,3,3,6,4,5,6,6,6,6},删除数组中元素6,结果: {1,2,3,3,4,5}
package com.wysheng.src1;
import java.util.Arrays;
/**
* @author Wang Yongsheng
* @version 1.0
* @date 2021/10/16 13:58
*/
public class TestDemo03 {
//删除头部
public static int[] removeHead(int[] arr) {
if(arr == null) {
return null;
}
for (int i = 0; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
int[] brr = new int[arr.length - 1];
for (int i = 0; i < arr.length - 1; i++) {
brr[i] = arr[i];
}
return brr;
}
//删除尾部
public static int[] removeTail(int arr[]) {
if(arr == null) {
return null;
}
int[] brr = new int[arr.length - 1];
for (int i = 0; i < brr.length; i++) {
brr[i] = arr[i];
}
return brr;
}
//删除特定值
public static int[] removeValue(int[] arr, int value) {
//安全检测
if (arr == null) {
return null;
}
int count = 0;
for (int i = 0; i < arr.length - count; ) {
if (arr[i] == value) {
count++;
for (int j = i + 1; j < arr.length; j++) {
arr[j - 1] = arr[j];
}
} else {
i++;
}
}
arr = Arrays.copyOf(arr,arr.length - count);
return arr;
}
public static void main(String[] args) {
int[] arr1 = {1,2,3,3,6,4,5,6,6,6,6};
System.out.println("------删除头部元素------");
int[] brr = removeHead(arr1);
System.out.println(Arrays.toString(brr));
System.out.println("------删除尾部元素------");
int[] arr2 = {1,2,3,3,6,4,5,6,6,6,6};
int[] crr = removeTail(arr2);
System.out.println(Arrays.toString(crr));
System.out.println("------删除特定元素------");
int[] arr3 = {1,2,3,3,6,4,5,6,6,6,6};
arr3 = removeValue(arr3, 6);
System.out.println(Arrays.toString(arr3));
}
}
运行结果:
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/95593.html