LeetCode 219 Contains Duplicate II
Posted SillyVicky
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 219 Contains Duplicate II相关的知识,希望对你有一定的参考价值。
Problem:
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 j is at most k.
Analysis:
给出数组nums,整型数k,找到数组中是否存在nums[i]和nums[j]相等且i - j小于k的情况。
Summary:
开始用最简单写法,两重for循环逐一查找,出现TLE。
后用HashMap改进,key为数组中出现的数字,value为最近出现位置的下标。
1 class Solution { 2 public: 3 bool containsNearbyDuplicate(vector<int>& nums, int k) { 4 int len = nums.size(); 5 unordered_map<int, int> m; 6 7 for (int i = 0; i < len; i++) { 8 if (m.find(nums[i]) != m.end() && i - m[nums[i]] <= k) { 9 return true; 10 } 11 else { 12 m[nums[i]] = i; 13 } 14 } 15 16 return false; 17 } 18 };
以上是关于LeetCode 219 Contains Duplicate II的主要内容,如果未能解决你的问题,请参考以下文章
219. Contains Duplicate II - LeetCode
LeetCode 219 Contains Duplicate II
[leetcode-219-Contains Duplicate II]
leetcode219 Contains Duplicate2