zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    day15—jQuery UI之widgets插件
    day14—jQuery UI 之dialog部件
    day13—CSS之导航栏
    day12—jQuery ui引入及初体验
    day11—前端学习之我不想看书
    struts2的action方法匹配以及通配符的使用
    Java中的static
    ActiveMQ的简单使用
    MS DOS 常用命令整理
    IntelliJ IDEA 中 Ctrl+Alt+Left/Right 失效
  • 原文地址:https://www.cnblogs.com/lailailai/p/4532191.html
Copyright © 2011-2022 走看看