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;
        }
    };
  • 相关阅读:
    分享几个原生javascript面向对象设计小游戏
    原生javascript模仿win8等待进度条。
    微信公众平台入门开发教程.Net(C#)框架
    AsyncDelegate
    Lock
    BackgroundWorker
    Thread
    深拷贝-浅拷贝
    WindowsService
    事件本质
  • 原文地址:https://www.cnblogs.com/LUO77/p/5046501.html
Copyright © 2011-2022 走看看