Partition Array by Odd and Even 373

Question

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.

Solution

前后指针。前指针从前往后遇到偶数停下,后指针从后往前遇到奇数停下,交换,继续,直到前后指针交叠。注意的地方是前指针从前往后走的时候要注意不要越界,后指针也一样。

代码如下:

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

results matching ""

    No results matching ""