您的位置:首页 > 大数据 > 人工智能

LeetCode | 219. Contains Duplicate II 循环技巧题高效率方法

2018-01-07 15:58 405 查看
Given an array of integers and an integer k, find out whether there aretwo distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference
between i and j is at most k.

这题,给你一个数组,问你这个数组里面有没有值相等,但是索引距离小于k的两个数存在,

我的方法beat 94.74%的人

我的思路是首先把数组排序,然后相同的数一定会相邻,当一个数和它相邻的数值相等的时候,比较他们在索引数组里面的索引的值的差是否小于k,如果小于则输出true,这里的索引数组用pair<int,int>来实现了,前一个int用来记录这个数的索引,后一个int用来记录这个数的值

class Solution {
public:
static bool cmp(pair<int, int> a, pair<int, int> b)
{
return b.second > a.second;
}
bool containsNearbyDuplicate(vector<int>& nums, int k) {
vector<pair<int, int>> number;
for (int i = 0; i < nums.size(); i++)
{
number.push_back(pair<int, int>(i, nums[i]));
}
sort(number.begin(), number.end(), cmp);
bool mark = false; int end;

for (int i = 0; i < number.size(); i++)
{
if (i + 1 < number.size() && number[i + 1].second == number[i].second)
{
end = i + 2;
while (end < number.size() && number[end].second == number[i].second) end++;
for(int l=i;l<end-1;l++)
for (int p = l + 1; p < end; p++)
{
if (abs(number[l].first - number[p].first) <= k) return true;
}
i = end;
}
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: