• leetcode 219


    219. 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 absolute difference between i and j is at most k.

    题意:给定一个数组和一个整数k,找出数组中是否存在两个距离不超过k的相同的数。存在返回true;反之,返回false.

    思路:我们首先想到的是将数组中的每个元素与它周围距离在k以内的元素对比,这样算法的时间复杂度为O(n2),算法效率太差。如果用set存放每次需要对比的数,那么每次查找的次数从k减少为logk,这样会大大提高效率。

    代码如下:

     1 class Solution {
     2 public:
     3     bool containsNearbyDuplicate(vector<int>& nums, int k) {
     4         set<int> s;
     5         if(k <= 0)
     6         {
     7             return false;
     8         }
     9         if(k >= nums.size())
    10         {
    11             k = nums.size() - 1;
    12         }
    13         for( int i = 0; i < nums.size(); i++ )
    14         {
    15             if( i > k )
    16             {
    17                 s.erase(nums[i - k - 1]);
    18             }
    19             if( s.find(nums[i]) != s.end())
    20             {
    21                 return true;
    22             }
    23             s.insert(nums[i]);
    24         }
    25         return false;
    26     }
    27 };
  • 相关阅读:
    [JLOI2015] 管道连接
    【知识点】斯坦纳树
    [ZJOI2010] 网络扩容
    【知识点】网络流常见模型
    [NOI2009] 植物大战僵尸
    [NOI2007] 货币兑换
    【知识点】分治相关算法
    [NOI2005] 月下柠檬树
    [HNOI2012] 射箭
    [SDOI2014] 向量集
  • 原文地址:https://www.cnblogs.com/shellfishsplace/p/6367990.html
Copyright © 2020-2023  润新知