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

    Summary:

    给出数组nums,整型数k,找到数组中是否存在nums[i]和nums[j]相等且i - j小于k的情况。

    Solution:

    开始用最简单写法,两重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 };
  • 相关阅读:
    urlencode 和 rawurlencode 的区别
    magic_quotes_gpc
    变量的值是多少
    git diff patch
    drupal前端开发的第一点
    git drupal eclipse
    spm总结
    features block
    alu features menu
    git reset 理解
  • 原文地址:https://www.cnblogs.com/VickyWang/p/6232277.html
Copyright © 2011-2022 走看看