zoukankan      html  css  js  c++  java
  • leetcode 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 difference between i and j is at most k

    这道题自己最后没有做出来,看的是【陆草纯】的解法。

    如果是JAVA的hashmap的话很简单,但是C++没有,之前我也想过用map按值排序,半天实现不了。

    先讲一下陆草纯的解法:

    构建一个map,如果nums里的元素在map里没有出现过的话,就先保存下标。

    如果出现过的话,就比较一下下标差值是否小于k。然后更新下标(每次都储存每个元素的最新下标)

    class Solution {
    public:
        bool containsNearbyDuplicate(vector<int>& nums, int k) {
            unordered_map<int,int> vec;
            int s=nums.size();
            if(s==0||k==0) return false;
            for(int i=0;i<s;i++){
                if(vec.find(nums[i])==vec.end()){
                    vec[nums[i]]=i;
                }
                else {
                    if(i-vec[nums[i]]<=k) return true;
                    vec[nums[i]]=i;
                }
            }
            return false;
        }
    };
  • 相关阅读:
    2019天梯赛训练1
    Python课程设计 搭建博客
    最容易理解的贪吃蛇小游戏
    数据结构-队列
    数据结构-堆栈(2)
    数据结构-堆栈(1)
    数据结构-线性表(3)
    数据结构-线性表(1)
    linux知识积累
    Maven学习笔记
  • 原文地址:https://www.cnblogs.com/LUO77/p/5046501.html
Copyright © 2011-2022 走看看