leetbook_ioa/docs/LCR 139. 训练计划 I.md
考虑定义双指针 $i$ , $j$ 分列数组左右两端,循环执行:
可始终保证: 指针 $i$ 左边都是奇数,指针 $j$ 右边都是偶数 。
下图中的
nums对应本题的actions。
{:align=center width=450}
<,,,,,,,,,,,,>
$x & 1$ 位运算 等价于 $x \mod 2$ 取余运算,即皆可用于判断数字奇偶性。
class Solution:
def trainingPlan(self, actions: List[int]) -> List[int]:
i, j = 0, len(actions) - 1
while i < j:
while i < j and actions[i] & 1 == 1: i += 1
while i < j and actions[j] & 1 == 0: j -= 1
actions[i], actions[j] = actions[j], actions[i]
return actions
class Solution {
public int[] trainingPlan(int[] actions) {
int i = 0, j = actions.length - 1, tmp;
while(i < j) {
while(i < j && (actions[i] & 1) == 1) i++;
while(i < j && (actions[j] & 1) == 0) j--;
tmp = actions[i];
actions[i] = actions[j];
actions[j] = tmp;
}
return actions;
}
}
class Solution {
public:
vector<int> trainingPlan(vector<int>& actions)
{
int i = 0, j = actions.size() - 1;
while (i < j)
{
while(i < j && (actions[i] & 1) == 1) i++;
while(i < j && (actions[j] & 1) == 0) j--;
swap(actions[i], actions[j]);
}
return actions;
}
};