mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
32 lines
1.3 KiB
Markdown
32 lines
1.3 KiB
Markdown
![]() |
# [219. Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/description/)
|
|||
|
# 思路
|
|||
|
判断数组是否有重复元素,而且重复元素下标差的绝对值不大于k,首先简单的思路就是用map,这里给出另一种解法:
|
|||
|
定义一个结构体num_with_index记录数组元素的值和下标,然后再对结构体按照值进行排序,排序后重复元素肯定相邻,再判断下标是否满足条件即可。
|
|||
|
# C++
|
|||
|
```
|
|||
|
class Solution {
|
|||
|
struct num_with_index{
|
|||
|
int num;
|
|||
|
int index;
|
|||
|
};
|
|||
|
public:
|
|||
|
// 这里必须加static否则编译不过,原因参考https://www.cnblogs.com/scoyer/p/6533685.html
|
|||
|
static bool mycompare(const num_with_index &a, const num_with_index &b){
|
|||
|
return a.num > b.num;
|
|||
|
}
|
|||
|
bool containsNearbyDuplicate(vector<int>& nums, int k) {
|
|||
|
vector<num_with_index>newnums;
|
|||
|
num_with_index newnum;
|
|||
|
for(int i = 0; i < nums.size(); i++){
|
|||
|
newnum.num = nums[i];
|
|||
|
newnum.index = i;
|
|||
|
newnums.push_back(newnum);
|
|||
|
}
|
|||
|
sort(newnums.begin(), newnums.end(), mycompare);
|
|||
|
for(int i = 1; i < nums.size(); i++)
|
|||
|
if(newnums[i].num == newnums[i-1].num && abs(newnums[i].index - newnums[i-1].index) <= k) return true;
|
|||
|
return false;
|
|||
|
}
|
|||
|
};
|
|||
|
```
|