剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
题目描述
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
示例:
输入:nums = [1,2,3,4]
输出:[1,3,2,4]
注:[3,1,2,4] 也是正确的答案之一。
提示:
0 <= nums.length <= 50000
1 <= nums[i] <= 10000
解题思路
使用双指针法,一个low一个high。
low从左向右寻找偶数,high从右向左寻找奇数。
因此,在low<high的循环中,做到:
low遇到奇数则low++;
high遇到偶数则high--;
low偶high奇则交换nums[low]和nums[high],然后low++,high--。
解题代码
class Solution:
def exchange(self, nums: list[int]) -> list[int]:
low, high = 0, len(nums) - 1
while low <= high:
result_low, result_high = nums[low] % 2, nums[high] % 2
if result_low != result_high:
if result_low == 0 and result_high == 1:
nums[low], nums[high] = nums[high], nums[low]
low += 1
high -= 1
elif result_low == result_high:
if result_low == 1:
low += 1
if result_high == 0:
high -= 1
return nums
执行结果
执行结果:通过
执行用时:64 ms, 在所有 Python3 提交中击败了33.42%的用户
内存消耗:18.9 MB, 在所有 Python3 提交中击败了47.70%的用户
共有 0 条评论