373. Partition Array by Odd and even "Lintcode Java"

Source: Internet
Author: User
Tags lintcode

Description

Partition an integers array into odd number first and even number second.

Example

Given [1, 2, 3, 4] , return[1, 3, 2, 4]

Challenge

Do it in-place.

Problem solving: Separate the odd and even numbers in an array, separating them in place and not applying for additional space. The idea is to record the last odd-numbered position, which can also be understood as the first of the even numbers. Iterates through an array, and does nothing if the elements in the current array are even numbers. If it is odd, it is exchanged with the number of records until the end of the loop. The code is as follows:

 Public classSolution {/** @param nums:an array of integers * @return: Nothing*/     Public voidPartitionarray (int[] nums) {        //Write your code here        intOdd_index = 0;//last singular value of the latter         for(inti = 0; i < nums.length; i++){            inttemp =Nums[i]; if(temp% 2 = = 1){                //if it's an odd numberNums[i] =Nums[odd_index]; Nums[odd_index]=temp; Odd_index++; }Else{                 //I don't do anything.            }        }    }}

373. Partition Array by Odd and even "Lintcode Java"

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.