Leetcode220-Contains Duplicate III

LeetCode 参考 Java版本 LeetCode 400题目 Java版本 (LeetCode is the platform to help you enhance your skills, expand your knowledge and prepare for technical interviews.) 立即下载

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.

题意

给一个整型数组,找到数组中是否存在两个元素,它们的下标差不超过k,元素值差不超过t。

分析

一开始对于每个元素,查找它后面k个元素是否与其值相差t以内。这样时间复杂度为O(kn),不能过超长数组的测试。所以可能存在O(nlogn)的算法。我的做法如下:

  • 首先给数组元素排序,并保留原有下标。示例如下:
0123–>2315
5312排序1235

* 维护一个特殊的队列(包括一个元素队列和下标队列)。该队列要求队首和队尾的元素值相差不超过t。具体操作:
* (1) 如队列为空则当前元素入队。
* (2) 如队头元素值与当前待入队元素值的差超过t,队头元素出队(因为经排序后,后面入队的元素值只会比当前元素更大,不可能出现与队首元素值差小于t的情况,所以队首元素已经没有继续存在在队列中的必要了)。
* (3) 如对头元素值与当前待入队元素值的差不超过t,则检查二者的下标差,如小于k,返回true,否则当前元素入队。
* (4) 最后队中剩余的元素只需比较队首与队尾的下标值即可。
* 时间复杂度。显然是排序的时间复杂度为O(nlogn),维护队列的过程每个元素出入队列一次。为O(n)。故总时间复杂度O(nlogn)。

TLE代码及AC代码

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        for (int i = 1; i < nums.size(); ++i) {
            for (int j = i - 1; j >= 0 && j > i - k; --j) {
                if (abs(nums[i] - nums[j]) <= t) { return true; }
            }
        }
        return false;
    }
};
//Time Limit Exceeded
class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        if (nums.empty()) return false;
        vector<int> order(nums.size());
        for (int i = 0; i != order.size(); ++i) {
            order[i] = i;
        }
        //sort nums and orders
        sortNumbers(nums, order, 0, nums.size() - 1);
        //push and pop
        queue<int> numsque;
        queue<int> orderque;
        //initialize queue
        numsque.push(nums[0]);
        orderque.push(order[0]);

        for (int i = 1; i < nums.size();) {
            if (numsque.empty()) {
                numsque.push(nums[i]);
                orderque.push(order[i]);
                ++i; continue;
            }
            int num = numsque.front();
            int ord = orderque.front();
            if (nums[i] > num + t) {
                numsque.pop();
                orderque.pop();

            } else {
                if (isOrderRangeSatisfactory(order[i], ord, k)) {
                    return true;
                } else {
                    numsque.push(nums[i]);
                    orderque.push(order[i]);
                    ++i;
                }
            }
        }

        int backOrder = orderque.back();
        int frontOrder = orderque.front();
        while (backOrder != frontOrder) {
            if (isOrderRangeSatisfactory(backOrder, frontOrder, k)) {
                break;
            }
            orderque.pop();
            frontOrder = orderque.front();
        }
        if (backOrder == frontOrder) {
            return false;
        } else {
            return true;
        }
    }

    bool isOrderRangeSatisfactory(int i, int j, int k) {
        return i <= j + k && i >= j - k;
    }

    void sortNumbers(vector<int> &nums, vector<int> &order, int bottom, int top) {
        if (bottom >= top) return;
        int i = bottom, j = top;
        int saveValue = nums[i];
        int saveIndex = order[i];
        while (i < j) {
            for (; i < j && nums[j] >= saveValue; --j);
            nums[i] = nums[j];
            order[i] = order[j];
            for (; i < j && nums[i] <= saveValue; ++i);
            nums[j] = nums[i];
            order[j] = order[i];
        }
        nums[i] = saveValue;
        order[i] = saveIndex;
        sortNumbers(nums, order, bottom, i - 1);
        sortNumbers(nums, order, i + 1, top);
    }
};
Leetcode-220:前100个最喜欢和最常问到的面试问题的解决方案 Leetcode Core 220 迭代问题: 随机播放 哈希图 指针 LRU / LFU缓存和Trie 带元组的队列/堆栈 单调堆栈/队列 级别顺序/ BFS /拓扑排序 ane 间隔 滑动窗口 递归问题: 分而治之 优先队列 快速选择/合并排序 联合发现 DFS /检查周期 递归和记忆 所有路径(回溯) 前100个最喜欢和最常问到的面试问题的解决方案。 团体 # 类别 # 问题 [R 一世 A.制表 1.1 组合DP 1个 55.跳棋 ✓ ✓ 递归/备注 2个 62.独特的道路 ✓ ✓ 3 64.最小路径总和 ✓ ✓ 4 70.爬楼梯 ✓ ✓ 5 91.解码方式 ✓ ✓ 6 118.帕斯卡的三角 ✓ ✓ 7 139.断字 ✓ ✓ 8 300.最长递增子序列 ✓ ✓ 9 322.硬币找零 ✓ ✓ 10 416.分区相等子集总和 ✓ 立即下载

相关推荐

FPGA实战:给你的UART串口通信加上Verilog奇偶校验位(Modelsim仿真验证)

本文详细介绍了如何在FPGA中实现UART串口通信的Verilog奇偶校验功能,包括发送端校验位生成和接收端校验检测的设计与实现。通过Modelsim仿真验证,确保数据传输的可靠性,适用于嵌入式系统和数字通信领域。

weixin_34216614的博客 341

桶排序(LeetCode220)

桶排序 1 介绍 桶排序(箱排序)是一种较优的排序算法,其工作原理是将数组分到有限数量的桶中。每个桶再分别排序,最后将桶按顺序输出即可得到有序的序列。桶排序比较适合数据发布均匀的数据集。 2 原理 基本原理再介绍部分以及阐述过,简单总结一下桶排序的特点。一个桶中可以存放不止一个元素,并且这些元素都属于某个范围内。例如1-5范围内的数字放到编号为1的桶中,6-10的数字放到编号为2的桶中,依次类推。桶中的数据可以通过链表连接起来。正是桶排序的这个特点,使得其更适合分布均匀的数据,否则数据间跨度较大,会导致许多

weixin_43716577的博客 700

X猫免费小说安卓逆向分析

七猫免费小说安卓逆向分析 难度(♥♥) 文章目录七猫免费小说安卓逆向分析 难度(♥♥)1. 查壳2. 抓包分析3. sign1. Frida-rpc2. Native函数分析快3点了. 睡觉~ 白天再继续写! 1. 查壳 我这边使用的是ApkTool, 拖进去显示未加壳。 2. 抓包分析 POST https://xiaoshuo.wtzw.com/api/v1/login/index HTTP/1.1 net-env: 1 channel: qm-cbcpa056_wm is-white: 0 platf

Qiled的博客 4366

【LeetCode】220.存在重复元素 (二叉搜索树方法+桶方法,java实现)

前言 本文中运用了平衡二叉搜索树,也是java里面的TreeSet数据结构。 也运用了桶。感兴趣的朋友可以了解一下。 题目 分析 概述 这篇文章是为中级读者准备的,文章中会介绍了以下几种方法: 二叉搜索树,散列表和桶。 方法一 (线性搜索) 【超时】 思路 将每个元素与它之前的 k个元素比较,查看它们的数值之差是不是在 t以内。 算法 解决这个问题需要找到一组满足以下条件的 i和 j: 我们需要维护了一个k大小的滑动窗口。这种情况下,第一个条件始终是满足的,只需要通过线性搜索来检查第二个条件是否满足就可

Viper的程序员修炼手册 930

Mac安装Typescript报错

根本原因是系统级目录的权限限制。推荐通过修改目录权限或使用nvm彻底解决问题。

江拥羡橙的博客 210

华为OD机试 C++【TLV解析】

这里的valueOffset指的是value在整串消息里的起始位置(从0开始数)。这表示tag是15(十六进制的0F),length是4,接着的8个字符是value的内容。你收到了一串由两端设备传递的TLV格式的消息,现在你需要根据这串消息生成一个对应的(tag, length, valueOffset)列表。tag是15,对应的数据长度为4,value从第3个字节开始,所以偏移量为2。第二行:一个数字n,表示我们给出的tag的数量(0 < n < 1000)。第一行:一串消息,长度不超过10000。

wtswts1232的博客 482

LeetCode第220题--存在重复元素 III

给定一个整数数组,判断数组中是否有两个不同的索引 i 和 j,使得 nums [i] 和 nums [j] 的差的绝对值最大为 t,并且 i 和 j 之间的差的绝对值最大为 ķ。 示例 1: 输入: nums = [1,2,3,1], k = 3, t = 0 输出: true 示例 2: 输入: nums = [1,0,1,1], k = 1, t = 2 输出: true 示例 3: 输入: ...

king3wade的博客 447

SpringBoot项目搭建

SpringBoot项目搭建

私信可回答各种问题~ 1020

LeetCode第220题_存在重复元素III

LeetCode第220题要求判断数组中是否存在两个不同下标的元素,其值的差的绝对值不超过t,且下标的差的绝对值不超过k。题目难度为中等,提供了两种主要解题思路: 滑动窗口 + 有序集合:通过维护一个大小不超过k的窗口,使用有序集合(如C#中的SortedSet或Python中的SortedList)来高效查找符合条件的元素。时间复杂度为O(n log(min(n, k))),空间复杂度为O(min(n, k))。 桶排序:将元素分配到大小为t+1的桶中,检查当前桶及相邻桶中是否存在满足条件的元素。

qq_40263592的博客 1475

【AI大模型】DeepSeek + Kimi 高效制作PPT实战详解

AI赋能,使用DeepSeek 高效制作PPT实战详解

congge 1万+

【七.三维视觉与视频分析】【1.点云处理:PointNet++/PointTransformer】

各位老铁,今天咱们要聊的可不是普通的二维图像处理,而是三维视觉领域最硬核的技术——点云处理。从最早的PointNet到如今的PointTransformer,这场技术进化堪比三维版的"像素革命"。今天咱们就深入解剖两大里程碑:PointNet++和PointTransformer,保证让你看完全文就能在点云领域横着走!想象一下,你抓了把沙子撒在空中,每粒沙子的位置都是三维坐标——这就是点云的典型形态。最后送大家一句话:点云处理就像在三维宇宙中寻找星辰的轨迹,既要望远镜的宏观视野,也要显微镜的细致入微。

商务合作|问题讨论|交流学习 请联系作者微信,加微信请务必注明来意,博客主页有联系方式 473

力扣(LeetCode)220. 存在重复元素 III(C++)

【墨染】滑动窗口&有序集合,降低枚举的时间瓶颈。

墨染 525

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

LeetCode 220 Contains Duplicate III

题目 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. Example1: Input: nums

weixin_42905061的博客 275

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

leetcode 220. Contains Duplicate III

220. Contains Duplicate III 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

_TFBoy的小茶馆 387

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

Leetcode 220. Contains Duplicate III (Medium) (cpp)

Leetcode 220. Contains Duplicate III (Medium) (cpp)

还是需要多学习!闷声大发财,这是坠吼的! 482

leetcode 220: Contains Duplicate III

leetcode 220: Contains Duplicate III java c++ python

西施豆腐渣 2万+

leetcode220. Contains Duplicate III

例如 AVL,能够让我们在最坏为 O(logk) 的复杂度内取得到最接近 u 的值是多少,但本题除了「查询」以外,还涉及频繁的「插入/删除」操作(随着我们遍历 nums 的元素,滑动窗口不断右移,我们需要不断的往「有序集合」中删除和添加元素)。或许你会想到近似 O(1) 操作的 HashMap,但注意这里我们需要找的是符合 abs(nums[i],nums[j])⩽t 的两个值,nums[i] 与 nums[j] 并不一定相等,而 HashMap 无法很好的支持「范围查询」操作。

weixin_44245188的博客 1162

Leetcode: 220. Contains Duplicate III

URLhttps://leetcode.com/problems/contains-duplicate-iii/description/描述Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference

zhumingyuan111的博客 209

Leetcode 220 Contains Duplicate III

Problem: 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 di...

Opium_Z的博客 196

LeetCode(220) Contains Duplicate III

题目Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j i

指尖飞舞 745

【leetcode】【medium】220. Contains Duplicate III

220.Contains Duplicate III Given an array of integers, find out whether there are two distinct indicesiandjin the array such that theabsolutedifference betweennums[i]andnums[j]is at mostt...

lemonade13的博客 182

LeetCode 220. Contains Duplicate III

思路分析: 首先,我选择HashSet这种数据结构。对数组nums遍历时,判断是否存在2个元素的差的绝对值小于等于t,若是,则返回true,否则,将元素加入set中,并维持更新set集的大小最大为k。set集中的元素一定是连续不相同的,若存在相同元素,进入循环体进行判断时,相同元素值差绝对值为0,一定小于t(t&amp;gt;=0),则满足所有条件返回true。 设x为set中的元素,-t &amp;lt;= n...

IT_BOY__的博客 246

【LEETCODE】220-Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array  such that the difference between nums[i] and nums[j] is at most t and the difference between i and

aliceyangxi1987的博客 676

[leetcode 220]Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i an

ER_Plough的专栏 764
上一篇: git整理commit的基本方法(拆分、合并、修改commit)
下一篇: 聚类算法概述(k-Means++/FCM/凝聚层次聚类/DBSCAN)
coderhuhy
博客等级 码龄12年 24粉丝 40原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值