LeetCode No.219 Contains Duplicate II

来源:互联网 发布:java源码阅读工具 编辑:程序博客网 时间:2024/05/17 00:08

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.

=========================================================

题目链接:https://leetcode.com/problems/contains-duplicate-ii/

题目大意:给定一个数组,求数组中是否存在j - i <= k使得nums[i] = nums[j]

思路:使用set记录前k个数值,每增加一个都需要将下标i - k - 1对应的数值从set中删掉。

参考代码:

class Solution {public:    bool containsNearbyDuplicate(vector<int>& nums, int k) {        int n = nums.size() ;        if ( n == 0 || k <= 0 )            return false ;        set <int> s ;        for ( int i = 0 ; i < n ; i ++ )        {            if ( i - k - 1 >= 0 )                s.erase ( nums[i-k-1] ) ;            if ( s.find ( nums[i] ) != s.end() )                return true ;            s.insert ( nums[i] ) ;        }        return false ;    }};


0 0
原创粉丝点击