第2章 排序 | 第14节 重复值判断练习题

题目


请设计一个高效算法,判断数组中是否有重复值。必须保证额外空间复杂度为O(1)。

给定一个int数组A及它的大小n,请返回它是否有重复值。
测试样例:

[1,2,3,4,5,5,6],7

返回:true

解析

class Checker {
public:
    bool checkDuplicate(vector<int> a, int n) {
        // write code here
        if(n<=1)
            return false;
        sort(a.begin(),a.end());
        for(int i=1;i<n;i++)
        {
            if(a[i]==a[i-1])
                return true;
        }
        return false;
    }
};
  • 参考代码用堆排序,不知道为什么
class Checker {
    void max_heapify(vector<int> &A, int l, int r) {
        int dad = l, son = 2 * dad + 1;
        while (son <= r) {
            if (son + 1 <= r && A[son + 1] > A[son]) ++son;
            if (A[dad] > A[son]) return;
            swap(A[dad], A[son]);
            dad = son;
            son = 2 * dad + 1;
        }
    }
    void heap_sort(vector<int> &A) {
        int n = A.size();
        for (int i = n / 2 - 1; i >= 0; --i)
            max_heapify(A, i, n - 1);
        for (int i = n - 1; i > 0; --i) {
            swap(A[0], A[i]);
            max_heapify(A, 0, i - 1);
        }
    }
public:
    bool checkDuplicate(vector<int> A, int n) {
        heap_sort(A);
        for (int i = 1; i < n; ++i)
            if (A[i] == A[i - 1]) return true;
        return false;
    }
};

猜你喜欢

转载自www.cnblogs.com/ranjiewen/p/9148159.html