连续数,创建一个函数来确定数组中的元素是否可以重新排列以形成一个连续的 数字列表,其中每个数字只出现一次

创建一个函数来确定数组中的元素是否可以重新排列以形成一个连续的
数字列表,其中每个数字只出现一次。
cons((5, 1, 4, 3, 21) › true // Can be re-arranged to form [1, 2, 3, 4, 51
cons(15, 1, 4, 3, 2, 81) - false
cons(15, 6, 7, 8, 9, 91) - false // 9 appears twice

img

先排序,然后判断数字是否连续递增且只出现一次,排序过程中,如果有相等的就直接返回false

img

代码:

#include<iostream>
using namespace std;
bool cons(int a[], int n)
{
    int i, j, t;
    //排序
    for (i = 0; i < n - 1; i++)
    {
        for (j = 0; j < n - i - 1; j++)
        {
            if (a[j] > a[j + 1])
            {
                t = a[j];
                a[j] = a[j + 1];
                a[j + 1] = t;
            }
            else if (a[j] == a[j + 1]) //有重复数字,直接返回false
                return false;
        }
    }
    //判断是否是连续数
    for (i = 1; i < n; i++)
    {
        if (a[i] - a[i - 1] != 1)
            return false;
    }
    return true;
}

int main()
{
    int a[100];
    int n;
    cout << "请输入数字元素个数:";
    cin >> n;
    cout << "请输入数组元素:";
    for (int i = 0; i < n; i++)
        cin >> a[i];
    if (cons(a, n))
        cout << "true" << endl;
    else
        cout << "false" << endl;
    return 0;
}

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632

凑热闹,c++11

#include<iostream>
#include<algorithm>
#include<vector>

bool IsAdjacenTest(std::vector<int>& p_vec)
{
    if (p_vec.empty())
        return false;
    // 排序
    std::sort(p_vec.begin(), p_vec.end());
    // 查找相邻重复元素
    auto iter = std::adjacent_find(p_vec.begin(), p_vec.end());
    if (iter != p_vec.end())
        return false;

    // 取巧版
    // 1,2,3,4,5    1+5=6  
    int nVecSize = p_vec.size();
    int nSumTemp = p_vec[0] + p_vec.size();
    int nSumVec = p_vec[0] + p_vec[p_vec.size() - 1];

    return (nSumVec == nSumTemp);
}

int main()
{
    std::vector<int> vec{ 1,2,5,3,7,9 };
    if (IsAdjacenTest(vec))
    {
        std::cout << "连续数" << std::endl;
    }
    else
    {
        std::cout << "不是连续数" << std::endl;
    }

    std::vector<int> vec1{ 1,2,5,3,4,6 };
    if (IsAdjacenTest(vec1))
    {
        std::cout << "连续数" << std::endl;
    }
    else
    {
        std::cout << "不是连续数" << std::endl;
    }

}