数据结构与算法之数据结构 数组删除 按值 / 按索引删除

数据结构与算法阿木 发布于 2025-07-11 11 次阅读


摘要:

数组作为一种基本的数据结构,在计算机科学中扮演着重要的角色。在处理数组时,删除操作是常见的需求之一。本文将深入探讨数组删除操作的两种常见策略:按值删除和按索引删除。通过分析不同语言的实现方式,我们将理解这些操作的原理,并学习如何高效地实现它们。

一、

数组是一种线性数据结构,它由一系列元素组成,每个元素都有一个唯一的索引。在处理数组时,删除操作是必不可少的。按值删除是指根据元素值来删除数组中的元素,而按索引删除则是根据元素的索引位置来删除。本文将详细介绍这两种删除策略的实现方法。

二、按值删除

按值删除的目的是从数组中删除所有与指定值相等的元素。以下是几种常见编程语言的实现方法:

1. Python

python

def remove_by_value(arr, value):


return [x for x in arr if x != value]

示例


array = [1, 2, 3, 4, 3, 5]


new_array = remove_by_value(array, 3)


print(new_array) 输出: [1, 2, 4, 5]


2. Java

java

public static int[] removeByValue(int[] arr, int value) {


List<Integer> list = new ArrayList<>();


for (int i = 0; i < arr.length; i++) {


if (arr[i] != value) {


list.add(arr[i]);


}


}


return list.stream().mapToInt(i -> i).toArray();


}

// 示例


int[] array = {1, 2, 3, 4, 3, 5};


int[] new_array = removeByValue(array, 3);


System.out.println(Arrays.toString(new_array)); // 输出: [1, 2, 4, 5]


3. C++

cpp

include <vector>


include <algorithm>

std::vector<int> removeByValue(std::vector<int>& arr, int value) {


arr.erase(std::remove(arr.begin(), arr.end(), value), arr.end());


return arr;


}

// 示例


std::vector<int> array = {1, 2, 3, 4, 3, 5};


array = removeByValue(array, 3);


std::cout << "{ ";


for (int i = 0; i < array.size(); i++) {


std::cout << array[i];


if (i < array.size() - 1) {


std::cout << ", ";


}


}


std::cout << " }" << std::endl; // 输出: { 1, 2, 4, 5 }


三、按索引删除

按索引删除是指根据元素的索引位置来删除数组中的元素。以下是几种常见编程语言的实现方法:

1. Python

python

def remove_by_index(arr, index):


return arr[:index] + arr[index+1:]

示例


array = [1, 2, 3, 4, 5]


new_array = remove_by_index(array, 2)


print(new_array) 输出: [1, 2, 4, 5]


2. Java

java

public static int[] removeByIndex(int[] arr, int index) {


int[] result = new int[arr.length - 1];


for (int i = 0, j = 0; i < arr.length; i++) {


if (i != index) {


result[j++] = arr[i];


}


}


return result;


}

// 示例


int[] array = {1, 2, 3, 4, 5};


int[] new_array = removeByIndex(array, 2);


System.out.println(Arrays.toString(new_array)); // 输出: [1, 2, 4, 5]


3. C++

cpp

include <vector>


include <algorithm>

std::vector<int> removeByIndex(std::vector<int>& arr, int index) {


arr.erase(arr.begin() + index);


return arr;


}

// 示例


std::vector<int> array = {1, 2, 3, 4, 5};


array = removeByIndex(array, 2);


std::cout << "{ ";


for (int i = 0; i < array.size(); i++) {


std::cout << array[i];


if (i < array.size() - 1) {


std::cout << ", ";


}


}


std::cout << " }" << std::endl; // 输出: { 1, 2, 4, 5 }


四、总结

本文详细介绍了数组删除操作的两种常见策略:按值删除和按索引删除。通过分析不同编程语言的实现方法,我们了解了这些操作的原理,并学习了如何高效地实现它们。在实际应用中,选择合适的删除策略取决于具体的需求和性能考虑。