码迷,mamicode.com
首页 > 编程语言 > 详细

373. Partition Array by Odd and Even【LintCode java】

时间:2018-07-14 13:02:09      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:not   challenge   nothing   inline   ram   app   HERE   bsp   color   

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.

解题:将一个数组中的奇数和偶数分开,原地分开,不申请额外的空间。思路是,记录好最后一个奇数的后一个位置,也可以理解为偶数中的第一个·。遍历数组,如果当前数组中的元素是偶数,那么什么也不干。如果是奇数,则与记录的那个数交换,直到循环结束。代码如下:

public class Solution {
    /*
     * @param nums: an array of integers
     * @return: nothing
     */
    public void partitionArray(int[] nums) {
        // write your code here
        int odd_index = 0;//最后一个奇数值的后一个
        for(int i = 0; i < nums.length; i++){
            int temp = nums[i];
            if(temp % 2 == 1){
                //如果是奇数
                nums[i] = nums[odd_index];
                nums[odd_index] = temp;
                odd_index++;
            }else{
                 //什么也不做   
            }
        }
    }
}

 

373. Partition Array by Odd and Even【LintCode java】

标签:not   challenge   nothing   inline   ram   app   HERE   bsp   color   

原文地址:https://www.cnblogs.com/phdeblog/p/9309171.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!