题目
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.
Note:
- 1 <= A.length <= 5000
- 0 <= A[ i ] <= 5000
给定一个非负整数数组A,对数组重新排序,使得偶数在前,奇数在后。可以返回任何一种满足这个条件的数组即可。
/**
* Question Link: https://leetcode.com/problems/sort-array-by-parity/
* Primary idea: traverse the array and insert Even into the 0 th index and odd into the last index
*
* Time Complexity: O(n), Space Complexity: O(n)
*
*/
class SortArrayByParity {
func sortArrayByParity(_ A: [Int]) -> [Int] {
//给定一个新数组
var outputArray = [Int]()
for (_,value) in A.enumerated(){
//遍历数组A,value为偶数则插入outputArray首位,如果是奇数则添加到数组末尾
outputArray.insert(value, at: value & 1 == 0 ? 0 : outputArray.count)
}
return outputArray
}
}
下一篇:Two Sum