zoukankan      html  css  js  c++  java
  • LeetCode 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.

      题目的大意:给你一个int型的数组和k,看看在数组中,是否有两个不同的索引i和j使得nums[i]=nums[j],i和j的差值,最多为k

    首先想到的办法是一个一个数字的比,两个for循环即可得到结果。但是这种方法耗时过长,提交后没过。这时需要考虑建一个multimap

    将数组的值和索引存到里面去,这样就快的多了。理所当然,提交也通过了

    class Solution {
    public:
       bool containsNearbyDuplicate(vector<int>& nums, int k) {
            if (nums.size()<2 || k<1)return false;
            else
            {
                multimap<int, int> mulm;
                for (int i = 0;i < nums.size();++i)
                    mulm.insert(make_pair(nums[i], i));
                for (int i = 0;i < nums.size();++i)
                {
                    auto cnt = mulm.count(nums[i]);
                    auto iter = mulm.find(nums[i]);
                    while (--cnt) {
                        int pre = iter->second;
                        int real = (++iter)->second-pre;
                        if (real <= k)return true;
                    }
                }
            }
            return false;
       }
    };
  • 相关阅读:
    mybatis-config.xml详解
    过滤器与拦截器
    Tomcat 部署web 项目
    Tomcat架构
    git stash
    AbstractQueuedSynchronizer 源码解读(转载)
    Kafka 转载
    Oracle数据库TNS详解
    Oracle建表知识全面详解
    Oracle高级教程
  • 原文地址:https://www.cnblogs.com/csudanli/p/5339650.html
Copyright © 2011-2022 走看看