项目作者: eMahtab

项目描述 :
Move Zeroes
高级语言:
项目地址: git://github.com/eMahtab/move-zeroes.git
创建时间: 2020-03-01T16:39:00Z
项目社区:https://github.com/eMahtab/move-zeroes

开源协议:

下载


Move Zeroes

https://leetcode.com/problems/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.

  1. Example:
  2. Input: [0,1,0,3,12]
  3. Output: [1,3,12,0,0]

Note:

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

Implementation 1 : Wrong Approach (Incorrect Result)

  1. class Solution {
  2. public void moveZeroes(int[] nums) {
  3. int zeroIndex = -1;
  4. for(int i = 0; i < nums.length; i++){
  5. if(nums[i] == 0){
  6. zeroIndex = i;
  7. } else{
  8. if(zeroIndex != -1){
  9. int tmp = nums[i];
  10. nums[i] = nums[zeroIndex];
  11. nums[zeroIndex] = tmp;
  12. zeroIndex = i;
  13. }
  14. }
  15. }
  16. }
  17. }

Implementation 2 : Right Approach (Correct Result)

  1. class Solution {
  2. public void moveZeroes(int[] nums) {
  3. int index = 0;
  4. for(int i = 0; i < nums.length; i++){
  5. if(nums[i] != 0){
  6. nums[index++] = nums[i];
  7. }
  8. }
  9. for(int i = index; i < nums.length; i++){
  10. nums[i] = 0;
  11. }
  12. }
  13. }

References :

https://www.youtube.com/watch?v=1PEncepEIoE