Leetcode-move Zeroes

Source: Internet
Author: User

Leetcode-move Zeroes

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.
classSolution { Public:    voidMovezeroes (vector<int>&nums) {        intpos =-1, i =0;  while(i<nums.size ()) {            if(Nums[i]! =0) {nums[++pos] =Nums[i]; } I++; }         while(pos+1<nums.size ()) {nums[++pos]=0; }    }};

Idea: First the non-zero number to the front, and record the last position of the non-zero, and then the other numbers are set to 0.

Time complexity O (n), Spatial complexity O (1)

Leetcode-move Zeroes

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.