Skip to content

Latest commit

 

History

History
 
 

n0922. Sort Array By Parity II

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Sort Array By Parity 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

解法

// Author: Netcan @ https://github.com/netcan/Leetcode-Rust
// Zhihu: https://www.zhihu.com/people/netcan

impl Solution {
    pub fn sort_array_by_parity_ii(a: Vec<i32>) -> Vec<i32> {
        let mut ret = Vec::with_capacity(a.len());
        unsafe { ret.set_len(a.len()); }
        let (mut i, mut j) = (0, 1);
        for n in &a {
            if n & 1 == 1 {
                ret[j] = *n;
                j += 2;
            } else {
                ret[i] = *n;
                i += 2;
            }
        }
        ret
    }
}