存在重复元素(C++解法)

题目

给你一个整数数组 nums 和一个整数 k ,判断数组中是否存在两个 不同的索引 i 和 j ,满足 nums[i] == nums[j] 且 abs(i - j) <= k 。如果存在,返回 true ;否则,返回 false 。

示例 1:

输入:nums = [1,2,3,1], k = 3
输出:true

示例 2:

输入:nums = [1,0,1,1], k = 1
输出:true

示例 3:

输入:nums = [1,2,3,1,2,3], k = 2
输出:false

C++代码

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

/*
* 重复元素问题
* 将数组元素与其索引建立联系,放入哈希表中
* 如果满足有相同元素并且索引之差的绝对值小于等于k,返回true
*/
bool containsNearbyDuplicate(vector<int>& nums, int k) {
	unordered_map<int, int> dictionary;
	int len = nums.size();
	for (int i = 0; i < len; ++i) {
		int num = nums[i];
		if (dictionary.count(num) && i - dictionary[num] <= k) {
			return true;
		}
		dictionary[num] = 1;
	}
	return false;
}

int main() {
	vector<int> nums = { 1,0,1,1 };
	int k = 1;
	bool ans = containsNearbyDuplicate(nums, k);
	cout << boolalpha << ans << endl;
	return 0;
}

分析

重复元素问题,将数组元素与其索引建立联系,放入哈希表中,如果满足有相同元素并且索引之差的绝对值小于等于 k,返回 true。如果不满足条件继续循环,并将新的联系覆盖。

猜你喜欢

转载自blog.csdn.net/m0_62275194/article/details/133963435
今日推荐