添加链接描述力扣,https://leetcode.cn/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/description/
双指针算法
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;
}
};