1. 程式人生 > >Leetcode 283. Move Zeroes

Leetcode 283. Move Zeroes

emp ber you elements public pla tco nbsp for

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.

一題目:

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].

Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.

二、分析

采用雙指針壓縮法:

把關註點放在非0元素上,而不是0。一個指針遍歷數組元素,找到非零元素。一個指針記錄壓縮的當前位置。整體就遍歷一次數據。

class Solution {
    public void moveZeroes(int[] nums) {
      int j = 0;
      for(int i=0; i<nums.length; i++) {
           
if(nums[i] != 0) { int temp = nums[j]; nums[j] = nums[i]; nums[i] = temp; j++; } } } }

Leetcode 283. Move Zeroes