輸入一個整數數組,實現一個函數來調整該數組中數字的順序,使得所有奇數位於數組的前半部分,所有偶數位於數組的後半部分。
示例:
輸入:nums = [1,2,3,4]
輸出:[1,3,2,4]
注:[3,1,2,4] 也是正確的答案之一。
提示:
1 <= nums.length <= 50000
1 <= nums[i] <= 10000
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路:遍歷
直接遍歷一遍數組,用兩個數組分別存儲奇數和偶數,最後遍歷完拼接即可。
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
ans_j = []
ans_o = []
for n in nums:
if n % 2 == 0:
ans_o.append(n)
else:
ans_j.append(n)
return ans_j + ans_o
思路2:雙指針
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
# 雙指針
i = 0
j = len(nums) - 1
while i < j:
while i < j:
if nums[i] % 2 == 0:
break
i += 1
while j > i:
if nums[j] % 2 == 1:
break
j -= 1
nums[i], nums[j] = nums[j], nums[i]
return nums