数组题 双指针
教练使用整数数组 actions 记录一系列核心肌群训练项目编号。为增强训练趣味性,需要将所有奇数编号训练项目调整至偶数编号训练项目之前。请将调整后的训练项目编号以 数组 形式返回
示例 1:
输入:actions = [1,2,3,4,5]
输出:[1,3,5,2,4]
解释:为正确答案之一
提示:
0 <= actions.length <= 50000
0 <= actions[i] <= 10000
public class Solution {
public int[] TrainingPlan(int[] actions) {
//看过队列的双向链表感觉题目思路是
//复制一个新数组 原数组遍历 遍历出来的奇数从前边放 遍历出来的偶数从后面放
//前面需要一个数组指针start 后面需要一个数组指针last
//注意数组针织和链表指针的区别
int [] temp=new int[actions.Length];//复制一个新数组,用来存排列后的数据
int start=0;//头指针
int last=actions.Length-1;//尾指针
for(int i=0;i<actions.Length;i++)
{
if(actions[i]%2==1)
{
temp[start]=actions[i];
start++;
}
}//这个循环找奇数,从前面放
for(int i=actions.Length-1;i>=0;i--)
{
if(actions[i]%2==0)
{
temp[last]=actions[i];
last--;
}
}//这个循环找偶数,从后面放
return temp;
}
}
第二种写法的双指针:
class Solution {
public int[] exchange(int[] nums) {
int len = nums.length;
int i = 0, j = len - 1;
while (i < j) {
if (nums[i] % 2 != 0) {
i++;
} else if (nums[j] % 2 == 0) {
j--;
} else {
//nums[i]是偶数nums[j]是奇数
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
return nums;
}
}