[leetcode]905. 按奇偶排序数组

1.题目:
给定一个非负整数数组 A,返回一个由 A 的所有偶数元素组成的数组,后面跟 A 的所有奇数元素。
Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.

2.代码:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* sortArrayByParity(int* A, int ASize, int* returnSize) {  
    *returnSize=ASize;
    int left=0,right=ASize-1;
    while(left<right){
        while(left<right&&A[left]%2==0)                  //偶数
            left++;
        while(left<right&&A[right]%2!=0)				 //奇数
            right--;
        int temp=A[left];
        A[left]=A[right];
        A[right]=temp;
        left++;
        right--;
    }  
    return A;
}

3.知识点:

快速排序思想。

猜你喜欢

转载自blog.csdn.net/MJ_Lee/article/details/88209027