剑指Offer|21. 调整数组顺序使奇数位于偶数前面【笔记】
链接
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] 也是正确的答案之一。
限制:
0 <= nums.length <= 50000 1 <= nums[i] <= 10000
关键
本人思路
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
nums.sort(key=lambda x:x%2==0)
return nums
思路1
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
odd = []
even = []
for i in nums:
if i%2==0:
even.append(i)
else:
odd.append(i)
return odd+even
思路2
- 首尾指针
- 首指针找偶数,尾指针找奇数,找到了就互换
- 注意跳出条件
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
left = 0
right = len(nums)-1
while left <= right:
while left <= right and nums[left]%2 == 1:
left += 1
while left <= right and nums[right]%2 ==0:
right -= 1
if left > right:
break
nums[left], nums[right] = nums[right], nums[left]
return nums
思路3
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
slow = fast = 0
while fast < len(nums):
if nums[fast]%2 == 1:
nums[slow], nums[fast] = nums[fast], nums[slow]
slow +=1
fast +=1
return nums
疑问
参考
[1] 剑指 Offer 21. 调整数组顺序使奇数位于偶数前面,辅助数组 + 头尾双指针 + 快慢双指针
|