LeetCode题解

时间:2021-03-11 12:06:51   收藏:0   阅读:0

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

/// <summary>
/// 首尾双指针法
/// </summary>
/// <param name="nums"></param>
/// <returns></returns>
public int[] HeadTailExchange(int[] nums)
{
    // 定义头指针 left ,尾指针 right ,临时变量 tmp 
    int left = 0;
    int right = nums.Length - 1;
    int tmp;
    // 重复操作,直到 left == right 为止
    while (left < right)
    {
        // left 一直往右移,直到它指向的值为偶数
        while (left < right && (nums[left] & 1) == 1)
        {
            left++;
        }
        // right 一直往左移, 直到它指向的值为奇数
        while (left < right && (nums[right] & 1) == 0)
        {
            right--;
        }
        // 交换
        tmp = nums[left];
        nums[left] = nums[right];
        nums[right] = tmp;
    }
    return nums;
}
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!