leetcode 219: Contains Duplicate II

来源:互联网 发布:知乎中文夹杂英文 编辑:程序博客网 时间:2024/06/14 12:59

解题思路:
遍历数组,把所有相同的数的下标都存储起来,然后对每个单独的数,计算其是否存在两个下标值小于k

原题目:

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.

AC解,C++代码,不过运行速度很慢,菜鸟一个,希望大家多多指正

class Solution {public:    bool containsNearbyDuplicate(vector<int>& nums, int k) {        map<int, int> value_index;        vector<vector<int>> index;        int ii = 0; //the index of index(vector)        for (int i = 0; i < nums.size(); i++) {            if(value_index.count(nums[i])) {                index[value_index[nums[i]]].push_back(i);            }            else {                vector<int> tuple;                tuple.push_back(i);                index.push_back(tuple);                value_index.insert(map<int, int>::value_type(nums[i], ii));                ii++;            }        }        for (int ii = 0; ii < index.size(); ii++) {            for(int j = 1; j < index[ii].size(); j++) {                if (index[ii][j] - index[ii][j - 1] <= k) {                    return true;                }            }        }        return false;    }};
0 0