今天天气不错,心情格外舒畅,刚刚刷了一道难度不大的题目,现在和大家分享一下经验。
题目如下:
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 absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
题意分析:
给定一个整数数组和一个整数k,判断是否存在两个相等元素的下标(两下标不可一样)之差的绝对值不超过k,最后返回bool型的true或false。
解答如下:
方法一(暴力解法)
用两层for循环“不重复”的遍历所有不同组合,并判断是否满足nums[i] == nums[j] && j - i <= k,是则返回true,否则继续遍历。直到所有组合都被遍历完都没找到,最后返回false。
class Solution{
public:
bool containsNearbyDuplicate( vector<int>& nums, int k ){
for ( int i = 0; i < nums.size(); i ++ ) {
for ( int j = i+1; j < nums.size(); j ++ ) {
if( nums[i] == nums[j] && j - i <= k )
return true;
}
}
return false;
}
};
提交后的结果如下:
日积月累,与君共进,增增小结,未完待续。