Skip to content
本页目录

21-调整数组顺序使奇数位于偶数前面

题目描述

https://leetcode.cn/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] 也是正确的答案之一。

提示:

0 <= nums.length <= 50000
0 <= nums[i] <= 10000

思路分析

基本思路: 左右下标指针,左边的遍历到偶数停止,右边遍历到奇数停止 两数交换,直到完成循环

实现代码

csharp
public class Solution {

    private bool IsOdd(int number){
        //return number % 2 > 0;
        return (number & 1) == 1; //使用位运算可以提交效率
    }

    public int[] Exchange(int[] nums) {
        int i = 0;
        int j = nums.Length-1;
        while(i < j){
            if(!IsOdd(nums[i]) && IsOdd(nums[j])){
                //swap
                int tmp = nums[i];
                nums[i] = nums[j];
                nums[j] = tmp;
                i++;
                j--;
            }
            else if(IsOdd(nums[i])){
                i++;
            }
            else if(!IsOdd(nums[j])){
                j--;
            }
        }
        return nums;
    }
}

Released under the MIT License.