package leetcode.sort;
/**
* @Description: 按奇偶排序数组
* 给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。
对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。
你可以返回任何满足上述条件的数组作为答案。
示例:
输入:[4,2,5,7]
输出:[4,5,2,7]
解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。
提示:
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-array-by-parity-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* @Param:
* @return:
* @Author: lvhong
* @Date:
* @E-mail lvhong282@163.com
*/
public class lab922 {
public static void main(String[] args) {
int in[] = {2, 0, 3, 4, 1, 3};
System.out.println(sortArrayByParityII(in));
}
/**
* @Description: 时间复杂度 O(n) 空间复杂度O(n)
* @Param:
* @return:
* @Author: lvhong
* @Date:
* @E-mail lvhong282@163.com
*/
// public int[] sortArrayByParityII(int[] A) { //两次递归,一次递归奇数,一次递归偶数
// int length = A.length;
// int pos=0;
// int [] out = new int[length];
// for(int num: A){
// if(num%2==0){
// out[pos]=num;
// pos+=2;
// }
// }
//
// pos=1;
// for(int num: A){
// if(num%2==1){
// out[pos]=num;
// pos+=2;
// }
// }
// return out;
// }
/**
* @Description: 时间复杂度 O(n) 空间复杂度O(1)
* @Param:
* @return:
* @Author: lvhong
* @Date:
* @E-mail lvhong282@163.com
*/
public static int[] sortArrayByParityII(int[] A) { //不需要额外空间,在数组内将奇数放到奇数位上,偶数放到偶数位上(保证奇数位上都是奇数即可,偶数位上也都是偶数,同理,偶数位上都是偶数,奇数位上也都是奇数)
int i = 0;
int length = A.length;
int pos = 1;
int temp ;
for (; i < length; i+=2) {
if (A[i] % 2 != 0) {
while(A[pos]%2==1){
pos+=2;
}
temp = A[i];
A[i] = A[pos];
A[pos] = temp;
}
}
return A;
}
}