今天刷了一道题,感觉还是有点难度的,下面就来总结一下经验吧!
题目如下:
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
题意分析:
给定一个整数数组,判断是否存在两个元素的下标(两下标不可一样)之差的绝对值不超过k,同时两元素的值之差的绝对值不超过t,满足条件返回true,否则继续遍历,直至遍历完仍没满足条件则返回false。
注:这里并不要求两元素是一样的值。
解答如下:
方法一(暴力解法)
用两层for循环“不重复”的遍历所有不同组合,当找到满足①:下标之差的绝对值不超过k;②值之差的绝对值不超过t;的组合时,则返回true,否则继续遍历,直至遍历完仍没满足条件则返回false。
注:当遇到测试用例,nums = [-1,2147483647]; k = 1; t = 2147483647时;会出现整型溢出,这时候需要用long long来强制转换类型予以避免。
class Solution{
public:
bool containsNearbyAlmostDuplicate( vector<int> nums, int k , int t){
for ( int i = 0; i < nums.size(); i ++ ) {
for ( int j = i+1; j < nums.size(); j ++ ) {
long long difference = abs((long long) nums[i]- (long long) nums[j]); //做加减法处均需要强制转换成long long
if( difference <= t && j - i <= k )
return true;
}
}
return false;
}
};
提交后的结果如下:
方法二(集合+滑动窗口)
为了满足下标之差的绝对值不超过k,所以创建一个集合用于记录区间长度为k的滑动窗口元素。为了满足值之差的绝对值不超过t,即需满足| nums[i] - nums[x] | <= t,nums[i] - t <= nums[x] <= nums[i] + t ,由于C++中只有“ceil操作”(lower_bound():求得括号内式子的最大值),所以只需要满足lower_bound(nums[i] - t)<= nums[i] + t 。
注:
①整型溢出问题;
②在判断lower_bound(nums[i] - t)<= nums[i] + t 的同时,要确保lower_bound(nums[i] - t)存在于集合中;
③集合读数需要加 *。
class Solution{
public:
bool containsNearbyAlmostDuplicate( vector<int> nums, int k , int t){
set<long long> record;
for ( int i = 0; i < nums.size(); i ++ ) {
if( record.lower_bound( (long long)nums[i] - (long long)t ) != record.end() && *record.lower_bound( (long long)nums[i] - (long long)t ) <= ((long long)nums[i] + (long long)t))
return true;
record.insert(nums[i]);
if( record.size() == k+1 ) //为了确保集合的区间长度始终为k
record.erase( nums[i-k] );
}
return false;
}
};
提交后的结果如下:
日积月累,与君共进,增增小结,未完待续。