排列前N個自然數,使得所有相鄰元素之間的絕對差 > 1?


我們有前 N 個自然數。我們的任務是獲得它們的某個排列,其中每個連續元素的絕對差 > 1。如果沒有這樣的排列,請返回 -1。

該方法很簡單。我們將使用貪心演算法。我們將按升序或降序排列所有奇數,然後按降序或升序排列所有偶數。

演算法

arrangeN(n)

Begin
   if N is 1, then return 1
   if N is 2 or 3, then return -1 as no such permutation is not present
   even_max and odd_max is set as max even and odd number less or equal to n
   arrange all odd numbers in descending order
   arrange all even numbers in descending order
End

示例

#include <iostream>
using namespace std;
void arrangeN(int N) {
   if (N == 1) { //if N is 1, only that will be placed
      cout << "1";
      return;
   }
   if (N == 2 || N == 3) { //for N = 2 and 3, no such permutation is available
      cout << "-1";
      return;
   }
   int even_max = -1, odd_max = -1;
   //find max even and odd which are less than or equal to N
   if (N % 2 == 0) {
      even_max = N;
      odd_max = N - 1;
   } else {
      odd_max = N;
      even_max = N - 1;
   }
   while (odd_max >= 1) { //print all odd numbers in decreasing order
      cout << odd_max << " ";
      odd_max -= 2;
   }
   while (even_max >= 2) { //print all even numbers in decreasing order
      cout << even_max << " ";
      even_max -= 2;
   }
}
int main() {
   int N = 8;
   arrangeN(N);
}

輸出

7 5 3 1 8 6 4 2

更新日期:2020 年 7 月 2 日

273 次瀏覽

啟動你的 職業生涯

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.