添加链接描述力扣,https://leetcode.cn/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/description/
双指针算法
Python
class Solution:
def trainingPlan(self, actions: List[int]) -> List[int]:
l, r = 0, len(actions) - 1
while l < r:
while l < r and actions[l] % 2 == 1:
l += 1
while l < r and actions[r] % 2 == 0:
r -= 1
actions[l], actions[r] = actions[r], actions[l]
return actions
Java
class Solution {
public int[] trainingPlan(int[] actions) {
if (actions.length < 2) {
return actions;
}
int left = 0, right = actions.length - 1;
while (left < right) {
if (actions[left] % 2 == 1) {
left++;
} else if (actions[right] % 2 == 0) {
right--;
} else if (actions[left] % 2 == 0 && actions[right] % 2 == 1) {
swap(left, right, actions);
left++;
right--;
} else {
break;
}
}
return actions;
}
public void swap(int i, int j, int[] array) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
Solution1:
顺序交换,比较好的算法!!!
class Solution {
public:
void reOrderArray(vector<int> &array) {
int n=array.size();
for(int i=0;i<n;i++){
if(array[i]%2==1){
int j=i;
while(j-1>=0 && array[j-1]%2==0){
swap(array[j-1],array[j]);
j--;
}
}
}
return;
}
public:
void swap(int &a,int &b){
int temp=a;
a=b;
b=temp;
return;
}
};