移除0元素

283. Move Zeroes

 

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

(ps:数字部分按照数组原顺序输出,不需要排序)

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations
    public class Solution {
        public void moveZeroes(int[] nums) {
           int j = 0;
    	    for (int i = 0; i < nums.length; i++) {
    			if (nums[i] != 0) {
    				nums[j] = nums[i];
    				j++;
    			}
    		}
    	    for (int i = j; i < nums.length; i++) {
    			nums[i] = 0;
    		}
    	   
        }
    }

移除数组元素有多种方法,以下为几种常见的实现方式及示例: ### 方法一:使用 JavaScript 的 splice() 函数 可利用 `splice()` 函数移除数组的元素。此方法接收两个必要参数:要删除元素的起始索引和要删除的元素数量。示例代码如下: ```javascript let arr = [1, 2, 3, 4, 5]; let index = 2; // 要删除的元素的索引 let count = 1; // 要删除的元素数量 arr.splice(index, count); console.log(arr); // 输出: [1, 2, 4, 5] ``` ### 方法二:使用 Java 传统循环遍历移动元素 在 Java 里,能通过传统的循环遍历,找到要移除元素,然后把后面的元素整体向前移动一位。示例代码如下: ```java public class Main { public static int removeElement(int[] nums, int val) { // 数组长度 int length = nums.length; // 外层遍历数组元素,查找要移除元素 for (int i = 0; i < length; i++) { if (nums[i] == val) { // 找到要移除元素,就将后面的元素整体向前移动一位 for (int j = i + 1; j < length; j++) { nums[j - 1] = nums[j]; } // 下标 i 后的数组元素均向前移动了一位,故 i 也向前移动一位 i--; // 数组长度-1 length--; } } return length; } public static void main(String[] args) { int[] nums = {1, 2, 3, 2, 4}; int val = 2; int newLength = removeElement(nums, val); for (int i = 0; i < newLength; i++) { System.out.print(nums[i] + " "); } } } ``` ### 方法三:使用双指针法 双指针法是一种常用的算法技巧,可高效地移除数组元素。以 Java 为例,左指针和右指针分别从数组两端开始扫描,当左指针指向要移除元素时,将右指针指向的元素赋值给左指针指向的位置,然后右指针左移。示例代码思路如下(以删除等于给定值 `val` 的元素为例): ```java public class Main { public static int removeElement(int[] nums, int val) { int left = 0; int right = nums.length; while (left < right) { if (nums[left] == val) { nums[left] = nums[right - 1]; right--; } else { left++; } } return left; } public static void main(String[] args) { int[] nums = {1, 2, 3, 2, 4}; int val = 2; int newLength = removeElement(nums, val); for (int i = 0; i < newLength; i++) { System.out.print(nums[i] + " "); } } } ``` 在这个代码中,使用了双指针的方法来删除数组中等于给定值 `val` 的元素。`left` 和 `right` 分别指向数组的头和尾。在算法执行过程中,左指针 `left` 从左往右扫描,右指针 `right` 从右往左扫描。当左右指针都扫描完数组时,算法结束 [^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值