Leecode 0905. Sort Array By Parity
905. Sort Array By Parity
Given an integer array nums
, move all the even integers at the beginning of the array followed by all the odd integers.
Return any array that satisfies this condition.
Example 1:
1 | Input: nums = [3,1,2,4] |
Example 2:
1 | Input: nums = [0] |
解法1:双指针
1 | class Solution |
解法2:库函数
1 | bool IsOdd(int n){ |
实现原理
std::partition
函数的工作原理:
- 重新排列范围内的元素,使满足谓词的元素(此处为偶数)出现在不满足谓词的元素(此处为奇数)之前
- 返回一个迭代器,指向第一个不满足谓词的元素(即第一个奇数的位置)
- 该算法采用不稳定排序,不保证元素之间的相对顺序
关键技术点
- 位运算判断奇偶:
n & 1
比n % 2 == 1
更高效- 对于整数,二进制最后一位为 1 则是奇数,为 0 则是偶数
- lambda 表达式作为谓词:
!IsOdd(n)
表示 "不是奇数",即 "是偶数"- 符合
std::partition
要求的谓词格式(返回 bool 值)
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.