LeetCode Contains Duplicate

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

class Solution {

public:

    bool containsDuplicate(vector<int>& nums) {

        int len = nums.size();

        if (len < 1) {

            return false;

        }

        sort(nums.begin(), nums.end());

        int prev = nums[0];

        for (int i=1; i<len; i++) {

            if (nums[i] == prev) {

                return true;

            }

            prev= nums[i];

        }

        return false;

    }

};

 发现选一个好实现的partition函数实在是太重要了:

class Solution {

public:

    bool containsDuplicate(vector<int>& nums) {

        int len = nums.size();

        if (len < 1) {

            return false;

        }

        quick_sort(nums, 0, len);

        int prev = nums[0];

        for (int i=1; i<len; i++) {

            if (nums[i] == prev) {

                return true;

            }

            prev= nums[i];

        }

        return false;

    }

    

    void quick_sort(vector<int>& nums, int start, int end) {

        if (start >= end) {

            return;

        }

        int di = partition(nums, start, end);

        quick_sort(nums, start, di);

        quick_sort(nums, di + 1, end);

    }

    

    int partition(vector<int>& nums, int start, int end) {

        if (start >= end) {

            return -1;

        }

        end--;

        swap(nums[(start + end) / 2], nums[end]);

        int pv = nums[end];

        int di = start;

        for (int i=start; i<end; i++) {

            if (nums[i] < pv) {

                swap(nums[i], nums[di++]);

            }

        }

        swap(nums[end], nums[di]);

        return di;

    }

};

 

你可能感兴趣的:(LeetCode)