为什么在数组中对偶数和奇数进行分区的算法不适用于围绕透视进行分区?



我们使用以下算法将所有偶数放到数组的左侧,将所有奇数放到数组的右侧:

def evenOddPartition(self,nums):
# partition an array such that all even are on the left
# and all odd are on the right
i = 0
j = len(nums) - 1
while i < j:
## if i is even skip this index
if nums[i]%2 == 0:
i+=1
elif nums[j] %2 == 0:
## if nums[i] is odd and nums[j] is even
nums[i],nums[j] = nums[j],nums[i]
j-= 1
else:
## both are odd 
## decrement j (i.e try to see if there is any other even before it)
j-=1
return nums

偶数/奇数是一种类似于真-假的二元分类。

我现在的问题是,为什么我们不能将同样的二进制分类应用于这样的问题:

考虑这个数组:y=[2,3,5]-100100,5,5,6,3,5]

并且要求您移动所有元素<=5到左侧,所有>5到右侧:

使用与偶数/奇数问题相同的逻辑,我给出了这个代码

def tryTwo(self,nums):
pivot = 5
i = 0
j = len(nums) - 1
while i < j:
if nums[i] < pivot:
i+=1
elif nums[i] == pivot:
i+=1
elif nums[i] > pivot:
if nums[j] <= pivot:
nums[i], nums[j] = nums[j], nums[i]
j-=1
else:
j-=1
else:
j-=1
return nums

但是,该代码输出[2,3,5,-100,5,5,3,6,100],这是错误的答案。正确的答案是这样的

[2,3,-100,3,5,5,5,5100,6]

我在这里错过了什么?我的第二个代码中有错误吗?

嗨:(你说过你得到的任务是

您被要求移动所有元素<=5到左侧,所有>5到右侧

这意味着输出[2, 3, 5, -100, 5, 5, 5, 3, 6, 100]完全有效。

所有小于等于5的元素都移动到列表的左侧

CCD_ 2。

其他人被移到右侧

6, 100]

正如Blastfurt所提到的,您的代码将6以下的每个数字都视为同一个数字,并且对这些数字没有任何排序机制。因此,3在5之后是有意义的(因为这些数字没有排序(。

如果你想要所有向左小于5,中间每隔5秒,向右大于5的元素,你需要一个不同的算法(或者只使用排序算法(。

最新更新