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;
    }
};

 直接使用hashmap

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_map<int, int> count;
        for (int i : nums) {
            if (++count[i] > 1) {
                return true;
            }
        }
        return false;
    }
};

 

posted @ 2015-05-27 00:23  卖程序的小歪  阅读(222)  评论(0编辑  收藏  举报