码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-easy-Partition Array by Odd and Even

时间:2016-03-03 09:07:49      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

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

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

public class Solution {
    /**
     * @param nums: an array of integers
     * @return: nothing
     */
    public void partitionArray(int[] nums) {
        // write your code here;
        
        if(nums == null || nums.length <= 1)
            return;
        
        int left = 0;
        int right = nums.length - 1;
        
        while(true){
            while(left < right && nums[left] % 2 != 0)
                left++;
            while(left < right && nums[right] % 2 == 0)
                right--;
            
            if(left == right)
                break;
            swap(nums, left, right);
        }
        
        return;
    }
    
    public void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
        
        return;
    }
    
}

 

lintcode-easy-Partition Array by Odd and Even

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5237196.html

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