leetcode#219 Contains Duplicate II

Source: Internet
Author: User

Problem Definition:

Given an array of integers and a integer K, find out whether there there is

Distinct indices i and J in the array such that nums[i] = Nums[j] and the difference between i and J are at the most K.

Solution 1:o (n^2) (report timeout)

1 defContainsnearbyduplicate (Nums, k):2n=Len (nums)3         ifn*k==0:4             returnFalse5I=06          whileI<n-1:7J=18              whilej<=K:9                 if(i+j) > (n-1):Ten                      Break One                 ifnums[i]==nums[i+J]: A                     returnTrue -                 Else: -J+=1 theI+=1 -         returnFalse

Solution 2: In the space for time, in the process of the array of values and values of the index in the formation of key-value pairs in the dictionary (dict), the time complexity of the dictionary query is O (1).

1DefContainsnearbyduplicate (self, nums, K):2 n =Len (nums)3If n*k==0:4ReturnFalse5 D ={}6For IInchRange (N):7If Nums[i]not in D: 8 D[nums[i]] = I 9 else< Span style= "color: #000000;" >:10 diff = ABS (d[nums[i]]-i) 11 if diff <= K:12 return True13 else:14 D[nums[i]] = I 15 return False        

leetcode#219 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.