Leetcode Move Zeroes

Source: Internet
Author: User

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

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

Note:

    1. You must does this in-place without making a copy of the array.
    2. Minimize The total number of operations.
Problem Solving Ideas:

Topics can be solved within O (n) Time complexity

Algorithm steps: x = i y = j

Use two "pointers" X and y, initial order y = 0

Use X to iterate through the array nums:

If NUMS[X] is not 0, then Exchange Nums[x] and Nums[y], and make y+1

Simple analysis of the algorithm:

The Y pointer points to the location where the first 0 elements may exist

During traversal, the algorithm ensures that elements in the [Y, X] range are 0

Java Code

 Public void movezeroes (int[] nums) {        int i = 0, j = 0;          for (i = 0; i< nums.length; i++) {            if(nums[i]! = 0)                {if(j! = i) {                     = nums[i];                     = 0;                }                J+ +;}}}    

Reference:

1. http://bookshadow.com/weblog/2015/09/19/leetcode-move-zeroes/

2. Https://leetcode.com/discuss/59543/move-zeros-solution-in-java

Leetcode Move Zeroes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.