zoukankan      html  css  js  c++  java
  • [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;
        }
    };
  • 相关阅读:
    Navicat Premium 12安装及破解(四)
    ajax原理及应用(十六)
    为什么每次下载后必须关闭掉IO流(十五)
    FormData提交文件(十四)
    代理设计模式(三)
    单例模式(二)
    工厂模式(一)
    集采用的验证规则
    java泛型的理解
    spring中如何直接注入session和request对像
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4863022.html
Copyright © 2011-2022 走看看