Leet专题刷题Day05-滑动窗口01
219. 存在重复元素 II
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; ++i) {
if (set.contains(nums[i])) return true;
set.add(nums[i]);
if (set.size() > k) {
set.remove(nums[i - k]);
}
}
return false;
}
}
643. 子数组最大平均数 I
思路:滑动窗口 减去前一个 加上后一个.
class Solution {
public double findMaxAverage(int[] nums, int k) {
int sum = 0;
for (int i = 0; i < k; i++) sum += nums[i];
int res = sum;
for (int i = k; i < nums.length; i++){
sum -= nums[i-k];
sum += nums[i];
res = Math.max(res, sum);
}
return res*1.0 / k;
}
}
3. 无重复字符的最长子串
思路:构建map 记录每一个char 出现的位置,i j 构建滑动窗口的前后,判断的时候要注意 得到的原来的位置大于i i才更新
class Solution {
public int lengthOfLongestSubstring(String s) {
char[] cc = s.toCharArray();
int res = 0;
Map<Character, Integer> map = new HashMap<>();
for (int i = 0, j = 0; j < cc.length; j++){
if (map.containsKey(cc[j])){
if (map.get(cc[j]) >= i) i = map.get(cc[j]) + 1;
map.put(cc[j], j);
}else{
map.put(cc[j], j);
}
res = Math.max(res, j-i+1);
}
return res;
}
}
220. 存在重复元素 III
思路 需要用的有序集合TreeSet顶层是红黑树,遇到的数 就判断是不是在 candidate-t 和 candidate +t之间.
class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
int n = nums.length;
TreeSet<Long> set = new TreeSet<Long>();
for (int i = 0; i < n; i++) {
Long ceiling = set.ceiling((long) nums[i] - (long) t);
if (ceiling != null && ceiling <= (long) nums[i] + (long) t) {
return true;
}
set.add((long) nums[i]);
if (i >= k) {
set.remove((long) nums[i - k]);
}
}
return false;
}
}