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;
        }
    };
  • 相关阅读:
    spring的常用配置
    aop切入点表达式
    代理模式
    hibernate的常用配置
    正则表达式
    Java配置
    性能提升
    创建vue3 项目
    manjaro
    单调队列
  • 原文地址:https://www.cnblogs.com/lailailai/p/4532191.html
Copyright © 2011-2022 走看看