📌  相关文章
📜  检查数组的元素是否可以连续差为1的圆排列

📅  最后修改于: 2021-06-26 00:14:27             🧑  作者: Mango

给定一个数组N 数字。任务是检查是否可以将所有数字排列成一个圆圈,以使任何两个相邻数字精确地相差1。如果可以的话,请打印“是”,否则请打印“否”。
例子:

Input: arr[] = {1, 2, 3, 2}
Output: YES
The circle formed is:
         1
     2       2
         3   

Input: arr[] = {3, 5, 8, 4, 7, 6, 4, 7}
Output: NO

以下是解决此问题的分步算法:

  1. 首先将所有元素插入到多集合中。
  2. 删除集合的第一个元素,并将其存储在curr变量中。
  3. 遍历直到多重集的大小减小为0。
    • 除去那些比CURR值小1大于或1个元素。
    • 如果差值大于1,则“不可能有圈”。
  4. 检查curr变量的初始值和最终值是否相同,如果相同,则打印“ YES”,否则打印“ NO”。

下面是上述方法的实现:

CPP
// C++ program to check if elements of array
// can be arranged in Circle with consecutive
// difference as 1
 
#include 
using namespace std;
 
// Function to check if elements of array can
// be arranged in Circle with consecutive
// difference as 1
int circlePossible(int arr[], int n)
{
    multiset s;
 
    // Initialize the multiset with array
    // elements
    for (int i = 0; i < n; i++)
        s.insert(arr[i]);
 
    // Get a pointer to first element
    int cur = *s.begin();
 
    // Store the first element in a temp variable
    int start = cur;
 
    // Remove the first element
    s.erase(s.begin());
 
    // Traverse until multiset is non-empty
    while (s.size()) {
 
        // Elements which are 1 greater than the
        // current element, remove their first occurrence
        // and increment curr
        if (s.find(cur + 1) != s.end())
            s.erase(s.find(++cur));
 
        // Elements which are 1 less than the
        // current element, remove their first occurrence
        // and decrement curr
        else if (s.find(cur - 1) != s.end())
            s.erase(s.find(--cur));
 
        // If the set is non-empty and contains element
        // which differs by curr from more than 1
        // then circle is not possible return
        else {
            cout << "NO";
            return 0;
        }
    }
 
    // Finally, check if curr and first differs by 1
    if (abs(cur - start) == 1)
        cout << "YES";
    else
        cout << "NO";
 
    return 0;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 1, 2, 2, 2, 3 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    circlePossible(arr, n);
 
    return 0;
}


输出:
YES

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。