Sword Finger Offer Interview Question 21. Adjust the array order so that odd numbers are in front of even numbers (double pointer)

Title description

Enter an array of integers and implement a function to adjust the order of numbers in the array so that all odd numbers are in the first half of the array and all even numbers are in the second half of the array.
Insert picture description here

Ideas

See link for details

Code

class Solution:
	def exchange(self, nums:List[int])->List[int]:
		i, j = 0, len(nums)-1
		while i<j:
			while i<j and nums[i] & 1 == 1:  #奇数
				i += 1
			while i<j and nums[j] & 1 == 0:   #偶数
				j -= 1
			nums[i], nums[j] = nums[j], nums[i]
		return nums
Published 227 original articles · praised 633 · 30,000+ views

Guess you like

Origin blog.csdn.net/weixin_37763870/article/details/105548358