LeetCode(easy)-905、Sort Array By Parity

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/f823154/article/details/82938045

905、Sort Array By Parity
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.
You may return any answer array that satisfies this condition.
Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
题目:
给定一个非负整数数组A,返回一个由A的所有偶数元素组成的数组,后跟A的所有奇数元素。
您可以返回满足此条件的任何数组答案。
例1:
输入:[3,1,2,4]
输出:[2,4,3,1]
输出[4,2,3,1],[2,4,1,3]和[4,2,1,3]也可以。
解法一:

//思路1:先分别得出奇偶数组,再组合到一起;
//思路2:奇偶交换数即可; 
//思路3:直接判断奇偶,将偶数从前往后排序,将奇数从后往前排序 
//Return an array of size *returnSize.
//Note: The returned array must be malloced, assume caller calls free().
//1:
int* sortArrayByParity(int* A, int ASize, int* returnSize) {
   *returnSize=ASize;
    int* temp=(int*)malloc(ASize*sizeof(int));
    int k=-1;
    for(int i=0;i<ASize;i++){
        if(A[i]%2==0){
            k++;
            temp[k] = A[i];
        }  
    }
    for(int j=0;j<ASize;j++){
        if(A[j]%2==1){
            k++;
            temp[k] = A[j];
        }  
    }
    return temp;
}
//2:
int* sortArrayByParity(int* A, int ASize, int* returnSize) {
   *returnSize=ASize;
    int* temp=(int*)malloc(ASize*sizeof(int));
    int i=0,j=ASize-1;
    while(i<j){
    	if(A[i]%2==0){
    		i++;
    		continue;
		}
		if(A[j]%2==1){
			j--;
			continue;
		}
		int tmp =A[i];
		A[i]=A[j];
		A[j]=tmp;
	}
	i++;
	j--;
	temp=A;
    return temp;
}
//3:
int* sortArrayByParity(int* A, int ASize, int* returnSize) {
   *returnSize=ASize;
    int* temp=(int*)malloc(ASize*sizeof(int));
    int j=0,k=ASize-1;
    for(int i=0;i<ASize;i++){        
        if(A[i]%2==0){            
            temp[j]=A[i];
            j++;        
        }   
        else{           
            temp[k]=A[i]; 
            k--;  
        }   
    }   
    return temp;
}

Runtime: 12 ms

猜你喜欢

转载自blog.csdn.net/f823154/article/details/82938045