How to rearrange data in array so that two similar items are not next to each other?

后端 未结 8 1962
暗喜
暗喜 2020-12-31 12:00

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

8条回答
  •  我在风中等你
    2020-12-31 12:11

    After I grasped what you're after, here's a possible solution

    1. Partition your array

      [1,1,1,8,8,8,2,3,3,4,1,1,1,2,2] -> [[3,1],[3,8],[1,2],[2,3],[1,4],[3,1],[2,2]]
      

      (read 3 times 1, 3 times 8, and so on)

    2. For each partition entry i with p[i][0] >1 (times >1):

      • Choose a "valid" position j (so p[j][1] != p[i][1] && p[j+1][1] != p[i][1])

      • Decrement p[i][0] element and insert [p[i][1],1] in partition at position j

      or leave it out if there is no such position.

    This should have linear time complexity (book-keep valid positions for each number).

提交回复
热议问题