• [LeetCode]18. Contains Duplicate II重复检测


    Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and jis at most k.

    解法1:首先想到的即是两重循环暴力破解,时间复杂度O(k*n)。

    class Solution {
    public:
        bool containsNearbyDuplicate(vector<int>& nums, int k) {
            int n = nums.size();
            if(n < 2 || k > n)
                return false;
            bool res = false;
            for(int i = 0; i < n; i++)
            {
                int m = n > i + k ? i + k : n - 1;
                for(int j = i + 1; j <= m; j++)
                {
                    if(nums[i] == nums[j])
                    {
                        res = true;
                        break;
                        break;
                    }
                }
            }
            return res;
        }
    };

    这个方法在数组很长时会Time Limit Exceeded

    解法2:考虑使用Hash表存储已经扫描过的元素。如果元素还没出现过,则存储下它在数组中的位置;如果已经存在,则存储下两个相同值的距离,然后判断这个距离是否小于k。

    class Solution {
    public:
        bool containsNearbyDuplicate(vector<int>& nums, int k) {
            int n = nums.size();
            if (n < 2)
                return false;
            bool res = false;
    
            map<int, int> mii;
            for (int i = 0; i < n; i++)
            {
                if (mii[nums[i]] == 0)
                {
                    if (i == 0)
                        mii[nums[i]] = -1;
                    else
                        mii[nums[i]] = i;
                }
                else
                {
                    if (mii[nums[i]] == -1)
                        mii[nums[i]] = i - mii[nums[i]] - 1;
                    else
                        mii[nums[i]] = i - mii[nums[i]];
                    if (abs(mii[nums[i]]) <= k)
                    {
                        res = true;
                        break;
                    }
                }
            }
            return res;
        }
    };
  • 相关阅读:
    【转】忘记密码功能的安全实现(邮件方式)
    windows7下安装gem包---bcrypt-ruby
    Ruby中的%表示法
    ruby中特殊的全局变量
    rails中一个窗体多个模型——fields_for
    【转】深刻理解render 和 redirect_to
    UML核心元素--分析类
    UML核心元素--包
    UML核心元素--边界
    UML核心元素--用例
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4863022.html
Copyright © 2020-2023  润新知