Leetcode:move Zeroes-Moves the 0 in the array to the last

Source: Internet
Author: User

1. Title

Move zeroes (move 0 in the array to the last)

2. Address of the topic

Https://leetcode.com/problems/move-zeroes

3. Topic content

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

English: Give an array of numbers, write a function to move all 0 of the array to the back of the non-0 items

For example: Given the array of nums = [0, 1, 0, 3, 12], after the function is called, the order of the elements of the arrays becomes [1, 3, 12, 0, 0].

Note: 1) You cannot copy a new array; 2) You need to minimize the number of operations.

4. Methods of Solving problems

The following two steps are required to complete a subject

1) Move the non-0 digits forward in turn

2) Fill in all the empty parts of the back 0

The Java code that implements this method is as follows:

/** *  function Description:leetcode 283 - move zeros *  developer:tsybius2014 *  Development Date: September 20, 2015  */public class solution {        / **     *  move the number 0 to the last      *  @param  nums  Input array      */    public void movezeroes (int[] nums)  {                // Move a non-0 number forward         int cur = 0;         for  (int i = 0; i < nums.length; i++)   {            if  (nums[i] != 0)  {                nums[ cur] = nums[i];                cur++;             }        }         //all the elements behind the 0        for   (int i = cur; i < nums.length; i++)  {             nums[i] = 0;         }    }}

END

Leetcode:move Zeroes-Moves the 0 in the array to the last

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.