剑指Offer—— 21.调整数组顺序使奇数位于偶数前面

题目如下

输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。

示例:

输入:nums = [1,2,3,4]
输出:[1,3,2,4]
注:[3,1,2,4] 也是正确的答案之一。


自己的算法和代码

(该算法课正确执行和提交,内存消耗较高,主要在创建了一个新的数组存放数据)

  • 创建一个新的数组 result[],和两个标志位 firstlast,分别指向 result[] 的 第 0 个位置,第 nums.length-1 个位置。
  • 从后向前遍历数组 nums。
    • 若 nums[i] 为偶数,则 添加到 result[] 的 last 位置,并让 last 前移一个位置,即 last--
    • 若 nums[i] 为奇数,则 添加到 result[] 的 first 位置,并让 last 后移一个位置,即 first++
  • 然后返回 result[]。
public class Solution {
    
    

    public static int[] exchange(int[] nums) {
    
    
        int[] result = new int[nums.length];
        int first = 0;
        int last = nums.length-1;
        for (int i = nums.length-1; i >= 0; i--){
    
    
            if (nums[i]%2 == 0){
    
    
                result[last] = nums[i];
                last--;
            }else {
    
    
                result[first] = nums[i];
                first++;
            }
        }
        return result;
    }

    public static void main(String[] args) {
    
    
        int[] nums = {
    
    1,2,3,4};
        int[] result = exchange(nums);
        for (int num : result){
    
    
            System.out.println(num);
        }
    }
}

参考的算法和代码

首尾双指针

  • 定义头指针 left ,尾指针 right .
  • left 一直往右移,直到它指向的值为偶数
  • right 一直往左移, 直到它指向的值为奇数
  • 交换 nums[left]nums[right] .
  • 重复上述操作,直到 left==right .
public class Solution {
    
    

    public static int[] exchange1(int[] nums) {
    
    

        int left = 0;
        int right = nums.length-1;
        int temp;
        while (left < right){
    
    
            if (nums[left]%2 != 0){
    
    	//奇数
                left++;
                continue;
            }
            if (nums[right]%2 == 0){
    
     //偶数
                right--;
                continue;
            }
            temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
        }
        return nums;
    }

    public static void main(String[] args) {
    
    
        int[] nums = {
    
    1,2,3,4};
        int[] result = exchange1(nums);
        for (int num : result){
    
    
            System.out.println(num);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/pary__for/article/details/114481626