zoukankan      html  css  js  c++  java
  • leetCode-Move Zeroes

    Description:
    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.

    My Solution:

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

    Another Better Solution:

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

    总结:
    用一个指针j表示非零元素的位置,注意和i对应的元素交换就可以了

    版权声明:本文为博主原创文章,未经博主允许不得转载。
  • 相关阅读:
    jq 京东跳楼效果
    *Sum of NestedInteger
    **Minimum Window Substring & String类问题模板
    **Word Ladder
    *Longest Increasing Subsequence
    *Kth Largest Element in an Array
    *Permutations II
    *Implement Stack using Queues
    *Paint House II
    *Paint Fence
  • 原文地址:https://www.cnblogs.com/kevincong/p/7881334.html
Copyright © 2011-2022 走看看