leetcode:Partition Array by odd and even

1、

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

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

2、思路

  1、通过两次遍历,不合算。

  2、一次遍历,一个从头,一个从尾,如果碰到偶数,兑换位置,此方法为排序。

3、

  

  public void partitionArray(int[] nums) {
       int start = 0, end = nums.length - 1;
            while (start < end) {
          //奇数的位置
while (start < end && nums[start] % 2 == 1) { start++; }
         //偶数的位置
while (start < end && nums[end] % 2 == 0) { end--; }
        //如果碰到偶数,调换位置,
if (start < end) { int temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; } } }

 

posted @ 2016-03-29 17:54  自朗活  阅读(162)  评论(0编辑  收藏  举报