【发布时间】:2019-07-01 09:16:30
【问题描述】:
给定一个数组,数组的元素代表猫和狗。我们必须通过交换重新排列元素,使相邻的位置没有两只猫或狗。
注意:我们可以将数组的元素与任何元素交换。
Eg: given input: [d,c,d,c,c]
exp o/p: 2
Explanation :
step 1: swap index-0 and index-1 =>[c,d,d,c,c]
step 2: swap index2 and index-3 =>[c,d,c,d,c]
input: [c,d,d,c,c,c]
exp o/p : not possible
【问题讨论】:
-
如果您可以将一个元素与任何其他元素交换,那么问题非常简单 O(n) 并且您可以很容易地找到它。就像您在第一个示例中所做的那样,您只能与相邻元素交换,这将更加困难。
标签: arrays algorithm data-structures