每日leetcode打卡(存在重复元素 III)难度:中等(第二天)

这篇博客讨论了LeetCode第220题《存在重复元素 III》的解决方案。作者提供了三种思路:暴力枚举(非最优),桶排策略,以及使用Treeset(基于红黑树)的方法。桶排策略中,通过元素大小确定桶的ID,并检查元素间距离是否小于等于k且差值小于等于t。Treeset的解决方案与桶排类似,但利用了数据结构的优势。文章提供了问题的背景、解释和相关代码实现。
摘要由CSDN通过智能技术生成

220.Contains Duplicate III

Given an integer array nums and two integers k and t, return true if there are two distinct indices i and j in the array such that abs(nums[i] - nums[j]) <= t and abs(i - j) <= k.
给你一个整数数组 nums 和两个整数 k 和 t 。请你判断是否存在两个下标 i 和 j,使得 abs(nums[i] - nums[j]) <= t ,同时又满足 abs(i - j) <= k 。
如果存在则返回 true,不存在返回 false。

思路:

1.暴力枚举(看看就行,卡int也不想改)

class Solution {
   
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
   
        int ans = nums.length;
            for(int i=0;i<ans-1;i++){
   
                for(int j=i+1; j<ans; j++){
   
                    if(Math.abs(nums[i] - nums[j]) <= t && Math.abs(i - j) <= k)
                    {
   
                    return true;
                    }
                }
            }
        return false;
    }
}

2.桶排

1.因为要满足nums[i] - nums[j]) <= t,所以桶的大小可以设为t+1,所以通过元素的大小来判断所在桶的id号

public long getID(long num, long t+1) {
   
    if (num 
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值