Leetcode Contains Duplicate II

Source: Internet
Author: User

Given an array of integers and a integer K, find out whether there is II distinct indices i and J in the array such that nums[i] = Nums[j] and the difference between I and Jare at most K.

The main idea of the topic: give you an int array and k, see if there are two different indexes in the array I and J make the difference between Nums[i]=nums[j],i and J, up to K

The first thing to think about is a one-digit ratio, with two for loops to get the results. But this method takes too long to submit. Then you need to consider building a Multimap

Save the value and index of the array inside, so it's much faster. Granted, the submission was also passed

classSolution { Public:   BOOLContainsnearbyduplicate (vector<int>& Nums,intk) {if(Nums.size () <2|| k<1)return false; Else{Multimap<int,int>Mulm;  for(inti =0; i < nums.size (); + +i) Mulm.insert (Make_pair (nums[i], i));  for(inti =0; i < nums.size (); + +i) {Auto CNT=Mulm.count (Nums[i]); Auto ITER=Mulm.find (Nums[i]);  while(--CNT) {                    intPre = Iter->second; intReal = (++iter)->second-Pre; if(Real <= k)return true; }            }        }        return false; }};

Leetcode Contains Duplicate II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.