Remove Element

简介: Remove Element删掉指定的元素,并用后面的元素顶替空出来的位置;Remove ElementGiven an array and a value, remove all instances of that value in place and return the new length.

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

目录
相关文章
|
6月前
'WebDriver' object has no attribute 'find_element_by_tag_name'
'WebDriver' object has no attribute 'find_element_by_tag_name'
301 0
|
12月前
|
JavaScript
Element UI报错:Unknown custom element: <el-menu>
Element UI报错:Unknown custom element: <el-menu>
165 0
|
JavaScript
element部分技巧总结
而v-if用来切换的元素是会被销毁的,导致了v-if内的表单项,由于在mounted时期没有进行渲染,所以规则也没有绑定上。初始化时不符合显示条件的不会生成规则,导致后面切换条件,显示的输入框的校验不会生效
Element Plus 相关
Element Plus 相关
119 0
|
Java C++
LeetCode之Remove Element
LeetCode之Remove Element
105 0
|
算法 C#
算法题丨Remove Element
描述 Given an array and a value, remove all instances of that value in-place and return the new length.
1042 0