Array--leetcode283

Source: Internet
Author: User

Topic

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 be[1, 3, 12, 0, 0]

Given an array, write a function that moves all 0 of the array to the end of the array, while maintaining the relative position of all other non-0 elements. Example input:[0,1,0,3,12] output:[1,3,12,0,0]

Code

Method One:

   public static void Movezeroes (int[] nums) {        int[] nonzeroelements = new Int[nums.length];        int count = 0;        for (int i = 0; i < nums.length; i++) {            if (nums[i]! = 0) {                Nonzeroelements[count] = nums[i];                count++;            }        }        for (int i = count; i < nums.length; i++) {            Nonzeroelements[count] = 0;            count++;        }        for (int i = 0; i < nums.length; i++) {            nums[i] = nonzeroelements[i];        }    }

  

Method Two:

   public static void Movezeroes (int[] nums) {        int size = 0;        for (int i = 0; i < nums.length; i++) {            if (Nums[i] > 0) {                nums[size] = nums[i];                size++;            }        }        for (int i = size; i < nums.length; i++) {            nums[i] = 0;        }    }

Method Three:

   public static void MoveZeroes3 (int[] nums) {        int k = 0;        for (int i = 0; i < nums.length; i++) {            if (Nums[i] > 0) {if                (i! = k) {   //If there is no 0 in the array, swap swap is not required                    (nums , I, k++);                } else {                    k++    ;    }}} public static void Swap (int[] arr, int i, int j) {        int temp = arr[i];        Arr[i] = arr[j];        ARR[J] = temp;    }

  

Array--leetcode283

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.