zoukankan      html  css  js  c++  java
  • LeetCode Contains Duplicate II

    Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.

    class Solution {
    public:
        bool containsNearbyDuplicate(vector<int>& nums, int k) {
            unordered_map<int, int> last;
            
            int len = nums.size();
            for (int i=0; i<len; i++) {
                int val = nums[i];
                auto iter = last.find(val);
                if (iter == last.end()) {
                    last.insert(make_pair(val, i));
                    continue;
                }
                if (i - iter->second <= k) {
                    return true;
                }
                iter->second = i;
            }
            return false;
        }
    };

     第二轮反而写的更挫了:

    class Solution {
    public:
        bool containsNearbyDuplicate(vector<int>& nums, int k) {
            unordered_set<int> count;
            int len = nums.size();
            k = min(++k, len);
            
            for (int i=0; i<len; i++) {
                if (i >= k) {
                    count.erase(nums[i-k]);
                }
                if (count.count(nums[i]) > 0) {
                    return true;
                }
                count.insert(nums[i]);
            }
            return false;
        }
    };
  • 相关阅读:
    js对象
    实习经历日志02
    前端实习经历日志01
    js变量提升
    WebApls-元素(offset, client, scroll)
    WebApls-Bom
    WebApls-DOM的核心总结
    WebApls-节点01
    javascript-
    Javascript-字符串对象
  • 原文地址:https://www.cnblogs.com/lailailai/p/4557563.html
Copyright © 2011-2022 走看看