LeetCode - RemoveElement

来源:互联网 发布:打出货单软件 编辑:程序博客网 时间:2024/06/06 13:04

/**

 * 问:给出一个数组,去除指定的某个元素,并返回新数组的长度。

 * 解:

 * 1、返回长度很简单,只有出现一个Element,length--即可,难点是如何删除元素。

 * 2、笨方法是再创建一个数组,存放不等于Element的元素。

 * 3、有一个空间复杂度为O(0)的方法:

 * (1)遍历数组时,出现Element后与数组最后一个元素交换。

 * (2)最关键的是:交换元素后立即i--和length--!

 */

public class RemoveElement {


public int removeElement(int[] array, int element) {

int length = array.length;

int temp;

// 遍历数组

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

if (array[i] == element) { // 当array[i]等于element时

// 交换array[i]和尾元素

temp = array[length-1];

array[length-1] = array[i];

array[i] = temp;

// 不仅记录新数组长度,同时也影响了循环范围。

length--;

// 尾元素被放在了array[i]上,需要再判断一次。

i--;

}

}

return length;

}


public static void main(String[] args) {

int[] array = {1, 2, 3, 4, 2, 6, 7, 9, 2};

int element = 2;

int length = new RemoveElement().removeElement(array, element);

System.out.println("删除" + element + "后新数组的长度是" + length + "。");

System.out.print("新数组是:");

for (int i=0; i<length; i++) 

System.out.print(array[i] + " ");

}


}
0 0