922. 按奇偶排序数组 II

给定一个非负整数数组 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] 也会被接受。

 

提示:

  1. 2 <= A.length <= 20000
  2. A.length % 2 == 0
  3. 0 <= A[i] <= 1000
import java.util.Stack;

public class Solution922 {
	public int[] sortArrayByParityII(int[] A) {

		int[] out = new int[A.length];
		Stack<Integer> odd = new Stack<>();
		Stack<Integer> even = new Stack<>();

		for (int i = 0; i < A.length; i++) {

			if (A[i] % 2 == 0) {
				even.add(A[i]);

			} else {
				odd.add(A[i]);
			}
		}
		for (int i = 0; i < out.length; i++) {

			if (i % 2 == 0) {
				out[i] = even.pop();

			} else {
				out[i] = odd.pop();
			}
		}

		return out;
	}

	public static void main(String[] args) {

		Solution922 s = new Solution922();

		int[] A = { 4, 2, 5, 7 };

		for (int n : A) {
			System.out.println(n);
		}

		System.out.println(s.sortArrayByParityII(A));

		for (int n : s.sortArrayByParityII(A)) {
			System.out.println(n);
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值