Leetcode 283. Move zeroes (mobile 0)

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.

Title Tags: Array, pointers

The topic gave us a nums array, let's move all 0 to the last side and keep the other numbers sorted.

Using the Pointers P1 and P2, the basic idea is to let the P2 stay in the 0 number, let P1 find not 0 of the number, swap P1 p2 value.

Traversing the nums array, when encountering 0 words, p1++, when encountering numbers that are not 0, swap P1 and P2 values, p1++ p2++.

Java Solution:

Runtime beats 74.14%

Completion Date: 04/27/2017

Key words: Array, pointers

Key point: Find a number that is not 0, with 0 permutation

1  Public classSolution2 {3      Public voidMovezeroes (int[] nums)4     {5         intP1 = 0;//Iterate each number6         intP2 = 0;//stop at 07         8          while(P1 <nums.length)9         {Ten             if(NUMS[P1]! = 0)//Find the Non-zero number One             { A                 if(P1! = p2)//swap Non-zero number with zero number -{//if p1 = p2, no need to swap -                     inttemp =NUMS[P1]; theNUMS[P1] =NUMS[P2]; -NUMS[P2] =temp; -                 } -                  +p2++; -             } +              Ap1++; at         } -  -     } -}

Reference: N/A

Leetcode algorithm topic List- leetcode algorithms Questions list

Leetcode 283. Move zeroes (mobile 0)

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.