Remove Element
删掉指定的元素,并用后面的元素顶替空出来的位置;
Remove Element
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
遍历数组;若元素nums[i]不等于指定数值val,保存此元素,游标newLengh加1
java代码:
1 package com.rust.cal; 2 3 public class RemoveElement { 4 public static int removeElement(int[] nums, int val) { 5 if (nums.length == 0) { 6 return 0; 7 } 8 int newLengh = 0; 9 for (int i = 0; i < nums.length; i++) { 10 if (nums[i] != val) { 11 nums[newLengh] = nums[i]; 12 newLengh++; 13 } 14 } 15 return newLengh; 16 } 17 public static void main(String args[]){ 18 int[] input = {4,5,8,4,5,4,9}; 19 int val = 4; 20 System.out.print("input = {"); 21 for (int i = 0; i < input.length - 1; i++) { 22 System.out.print(input[i] + ", "); 23 } 24 System.out.print(input[input.length - 1] + "}"); 25 System.out.println("\n" + "val = 4"); 26 System.out.println("new lengh = " + removeElement(input, val)); 27 System.out.print("output : "); 28 for (int i = 0; i < input.length; i++) { 29 System.out.print(input[i] + "\t"); 30 } 31 } 32 }
控制台输出:
input = {4, 5, 8, 4, 5, 4, 9}
val = 4
new lengh = 4
output : 5 8 5 9 5 4 9