题目链接:https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
输入:nums = [1,2,3,4]
输出:[1,3,2,4]
注:[3,1,2,4] 也是正确的答案之一。
解题过程:
第一次:
使用两个数组分开存,然后再合并。天真的我以为用ArrayList
会快一点,谁知道写的这么麻烦。。。。
class Solution {
public int[] exchange(int[] nums) {
ArrayList<Integer> odd = new ArrayList<>();
ArrayList<Integer> even = new ArrayList<>();
for (int num : nums){
if (num % 2 == 0){
even.add(num);
}else {
odd.add(num);
}
}
odd.addAll(even);
return odd.stream().mapToInt(Integer::intValue).toArray();
}
}
第二次
思路一样,比上面快了一点。
class Solution {
public int[] exchange(int[] nums) {
ArrayList<Integer> odd = new ArrayList<>();
ArrayList<Integer> even = new ArrayList<>();
for (int num : nums){
if (num % 2 == 0){
even.add(num);
}else {
odd.add(num);
}
}
int[] res = new int[nums.length];
for (int i = 0; i < odd.size(); i++){
res[i] = odd.get(i);
}
for (int i = 0; i < even.size(); i++){
res[odd.size() + i] = even.get(i);
}
return res;
}
}
第三次:
又快了一点。。。
class Solution {
public int[] exchange(int[] nums) {
int len = nums.length;
int[] res = new int[len];
int i = 0;
for (int num : nums){
if (num % 2 != 0){
res[i] = num;
i++;
}
}
for (int num : nums){
if (num % 2 == 0){
res[i] = num;
i++;
}
}
return res;
}
}
第四次:
时间上没变,但内存减少了一点。不过这种方法是我觉得这里面最高大上的一种,前面的三种方法无非就是遍历数组,另外存储,而这种方法不一样。
看代码发现,思路类似于快速排序。这道题挺适合用这种方法求解的。
从前寻找偶数,从后寻找奇数,找到后如果满足条件则把两个数调换位置。
class Solution {
public int[] exchange(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right){
while(left < right && nums[left] % 2 != 0){ // 从左边寻找偶数
left++;
}
while(left < right && nums[right] % 2 == 0){ // 从右边寻找奇数
right--;
}
if (left < right) { // 保证左边奇数,右边偶数
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
}
return nums;
}
}