1. 程式人生 > >LeetCode(easy)-905、Sort Array By Parity

LeetCode(easy)-905、Sort Array By Parity

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