题目的链接在这里:https://www.nowcoder.com/practice/ef1f53ef31ca408cada5093c8780f44b
- 题目大意
- 一、示意图
- 二、解题思路
- 队列
- 双指针
题目大意 输入一个长度为 n 整数数组,数组里面不含有相同的元素,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前面部分,所有的偶数位于数组的后面部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
数据范围:0 le n le 50000≤n≤5000,数组中每个数的值 0 le val le 100000≤val≤10000
要求:时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)
进阶:时间复杂度 O(n^2)O(n
2
),空间复杂度 O(1)O(1)
一、示意图 二、解题思路
队列和双指针队列
代码如下:
import java.util.*;
public class Solution {
public int[] reOrderArray (int[] array) {
// write code here
//让奇数在偶数的前面奇数和偶数的相对位置不变 用
//用两个队列
Queue One_array=new linkedList<>();
Queue Two_array=new linkedList<>();
//开始遍历
for(int temp:array){
if(temp%2==0){
One_array.add(temp);
}
else{
Two_array.add(temp);
}
}
//然后在遍历输出
int i=0;
int[] res=new int[array.length];
while (!Two_array.isEmpty()){
res[i++]=Two_array.poll();
}
while (!One_array.isEmpty()){
res[i++]=One_array.poll();
}
return res;
}
}
双指针
代码如下:
import java.util.*;
public class Solution {
public int[] reOrderArray(int[] array) {
//还要一个方法 单数从前往后开始遍历 双数从后往前开始遍历
int[] res=new int[array.length];
int left=0;
int right=array.length-1;
for(int i=0;i


![java 剑指offer之[数据结构 简单]JZ21 调整数组顺序使奇数位于偶数前面(一) java 剑指offer之[数据结构 简单]JZ21 调整数组顺序使奇数位于偶数前面(一)](http://www.mshxw.com/aiimages/31/342947.png)
