Leetcode Note: Move Zeroes

Source: Internet
Author: User

Leetcode Note: Move Zeroes

I. Description

Given an array nums, write a function to move all0'sTo the end of it while maintaining the relative order of the non-zero elements.

For example, givennums = [0, 1, 0, 3, 12], After calling your function, nums shoshould 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.

Ii. Question Analysis

The meaning of the question is very clear. Given an array, adjust the non-zero element to the front, and place the zero element behind the array. In-situ operations are required and as few operations as possible.

The question is relatively simple. You only need to scan the array once and use an integer variable in this process.IndexRecords the number of non-zero elements. Each time a non-zero number is encountered, it is placed innums[Index]And thenIndexAdd1.

After the traversal,numsThe position of the non-zero element has been determined. You only need to set the half of the array to zero.IndexRecords the number of non-zero elements, so it is convenient to set the value to zero.

Iii. Sample Code

class Solution {public:    void moveZeroes(vector
  
   & nums) {        if (nums.size() < 1) return;          int Index = 0;        for (int i = 0; i < nums.size(); ++i)             if (nums[i] != 0)                 nums[Index++] = nums[i];        for (;Index < nums.size(); ++Index)             nums[Index] = 0;    }};
  

Iv. Summary

For such problems, in-situ operations and as few operations as possible are generally required.

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.