Leetcode:move Zeroes

Source: Internet
Author: User

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-zer o elements.  = [0, 1, 0, 3, a], after calling your function, nums should be [1, 3, a, 0, 0 do this in-Placewithout making a copy of the array. Minimize The total number of operations.

Pointer L,r,

L was to find each 0 in the list, and R is to start from L, find first non-0

L, R should not both start from 0, because if R was to the left of L, we don ' t want to swap it. Example: [1, 0]

1  Public classSolution {2      Public voidMovezeroes (int[] nums) {3         if(nums==NULL&& nums.length==0)return;4         intL=0, r=0;5          while(L < nums.length && R <nums.length) {6              while(L<nums.length && nums[l]!=0) {7l++;8             }9R =l;Ten              while(R<nums.length && nums[r]==0) { Oner++; A             } -             if(L = = Nums.length | | r = = nums.length) Break; - Swap (Nums, L, R); the         } -     } -      -      Public voidSwapint[] Nums,intLintr) { +         inttemp =Nums[l]; -NUMS[L] =Nums[r]; +NUMS[R] =temp; A     } at}

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.