[Leetcode] 283. Move Zeroes Zero

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.

For example, given nums = [0, 1, 0, 3, and 1], after calling your function, Nums should is [3, 12, 0, 0,].

Note:

You must does this in-place without making a copy of the array.
Minimize The total number of operations.

Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and creating all test cases.

Moving all 0 of an array to the back, cannot change the relative positional relationship of non-zero, and cannot copy additional arrays.

To use the substitution method In-place, double pointer to do, the front pointer to the last non-0 number of processing, the back of a pointer to sweep backward, encountered a non-0 number, and the front pointer refers to the digital exchange position, the front pointer moves 1 bits behind.

Or do not exchange only the non-zero number to the front, the final unification of the back of all into 0.

Java:time complexity:o (n), Space complixity:o (1)

public class Solution {public    void Movezeroes (int[] nums) {        int index = 0;        for (int i = 0; i < nums.length; ++i) {            if (nums[i]! = 0) {                nums[index++] = nums[i];            }        }        for (int i = index; i < nums.length; ++i) {            nums[i] = 0;}}}    

Python:

Class solution (Object):    def movezeroes (self, Nums): "" "        : Type Nums:list[int]        : Rtype:void does not Return anything, modify Nums in-place instead.        "" pos = 0        for i in Xrange (Len (nums)):            if nums[i]:                nums[i], nums[pos] = Nums[pos], Nums[i]                pos + = 1

C++:

Class Solution {public:    void Movezeroes (vector<int>& nums) {        int pos = 0;        for (auto& num:nums) {            if (num) {                swap (nums[pos++], num);}}}    ;

[Leetcode] 283. Move Zeroes Zero

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.