如何重新排列数组中的数据,以使两个相似的项彼此不相邻? [英] How to rearrange data in array so that two similar items are not next to each other?

查看:359
本文介绍了如何重新排列数组中的数据,以使两个相似的项彼此不相邻?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只想重新排列数组中的数据,以使相似的项目不紧挨着每个项目。数据不应从数组中删除,如果无法重新排列,可以将其放在数组的末尾。但是必须保持原始顺序。

Just want to rearrange the data in array so that similar items are not next to each. The data should not be removed from the array, if it can't be rearranged it can be put at the end of the array. But keeping the original order is necessary.

示例

   1 1 2             =>   1 2 1 
   1 1 1 2 3         =>   1 2 1 3 1
   1 1 2 1 3 3 5 1   =>   1 2 1 3 1 3 5 1
   1 1 1 1 1 1 2     =>   1 2 1 1 1 1 1
   8 2 1 3 7 2 5     =>   rearrange not needed
   8 2 2 2 7 2 5 2   =>   8 2 7 2 5 2 2      // keep the original order

编辑:
添加了示例来显示需要保持原始顺序

Added example to show keeping original order is needed

推荐答案


  1. 对数组进行排序

  2. 以较小的偶数索引与较高的对映体交换元素:

  1. Sort your array
  2. Swap elements at small even indexes with their higher antipodal counterparts:

for ( i=0; i < arr.length/2; i+=2 )
    arr.swap(i,arr.length-1-i);


编辑:好的,我们应该重新定义对映体同行。也许这样比较好:混合第一和第三四分位数(在图中表示为x,y),并混合第二和第三四分位数(表示为u,v,w)。

Okay, we should redefine the antipodal counterparts. Maybe this one is better: mixing the first and third quartile (denoted x, y in illustration), and mixing the second and third quartile (denoted u, v, w). Let the counterparts ascend parallel.

        25%  50%  75%
         |    |    |
    -----[----[----[----
    11122334455667788999
     x y u v w x y u v w  <-- u, v, w, x, y indicate swap positions
    16172839495161738495

这篇关于如何重新排列数组中的数据,以使两个相似的项彼此不相邻?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆