LeetCode算法题-K-diff Pairs in an Array(Java实现)

【COMSOL】将一个面上数据导出CSV或txt格式的方法 在COMSOL中参数化扫描后,把一个面上或体里的数据按照CSV或TXT格式导出的方法。 阅读详情

这是悦乐书的第254次更新,第267篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第121题(顺位题号是532)。给定一个整数数组和一个整数k,您需要找到数组中唯一的k-diff对的数量。 这里k-diff对被定义为整数对(i,j),其中i和j都是数组中的数字,它们的绝对差是k。例如:

输入:[3,1,4,1,5],k = 2
输出:2
说明:数组中有两个2-diff对,(1,3)和(3,5)。虽然我们在输入中有两个1,但我们应该只返回唯一对的数量。

输入:[1,2,3,4,5],k = 1
输出:4
说明:数组中有四个1-diff对,(1,2),(2,3),(3,4)和(4,5)。

输入:[1,3,1,5,4],k = 0
输出:1
说明:数组中有一个0-diff对,(1,1)。

注意:

  • 对(i,j)和(j,i)计为同一对。

  • 数组的长度不会超过10,000。

  • 给定输入中的所有整数都属于以下范围:[-1e7, 1e7]。

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 第一种解法

暴力解法。先排序,然后使用两层循环,计算不同元素的绝对值,如果等于k,次数就加1。在外面第一层循环那里,如果前后元素相同,就跳过当前循环,进行下一次循环。在内层循环那里同样做了类似的判断,排除重复计算。

此解法的时间复杂度是O(n^2),空间复杂度是O(1)。

public int findPairs(int[] nums, int k) {
    if (nums == null || nums.length == 0 || k < 0) {
        return 0;
    }
    Arrays.sort(nums);
    int count = 0;
    for (int i=0; i<nums.length; i++) {
        int n = nums[i];
        if (i >= 1 && nums[i-1] == nums[i]) {
            continue;
        }
        for (int j=i+1; j<nums.length; j++) {
            if (j >= i+2 && nums[j-1] == nums[j]) {
                continue;
            }
            if (Math.abs(n - nums[j]) == k) {
                count++;
            }
        }
    }
    return count;
}

03 第二种解法

第一种解法时间复杂度太高了,得降低点。第一种解法,我们是做减法,求绝对值,来判断是否等于k,我们也可以做加法,拿当前元素加上k,然后看新元素是否存在于数组中。同时还要考虑重复的计算数据,因此参与计算的元素是唯一的,对此我们可以使用HashMap,已元素值作为key,该元素值出现次数为value。遍历key,如果key加上k后的值存在于map中,次数加1,另外如果k为0的时候,只需要判断每个key所对应的value是否大于等于2即可。

此解法的时间复杂度是O(n),最坏情况也可能是O(n^2),空间复杂度是O(n)。

public int findPairs2(int[] nums, int k) {
    if (nums == null || nums.length == 0 || k < 0) {
        return 0;
    }
    Map<Integer,Integer> map = new HashMap<Integer,Integer>();
    for (int n : nums) {
        map.put(n, map.getOrDefault(n, 0)+1);
    }
    int count = 0;
    if (k == 0) {
        for (Integer key: map.keySet()) {
            if (map.get(key) >= 2) {
                count++;
            }
        }
    } else {
        for (Integer key: map.keySet()) {
            if (map.containsKey(key+k)) {
                count++;
            }
        }
    }
    return count;
}

04 第三种解法

对于第二种解法,还可以将判断放在循环体里面。

public int findPairs3(int[] nums, int k) {
    if (nums == null || nums.length == 0 || k < 0) {
        return 0;
    }
    Map<Integer,Integer> map = new HashMap<Integer,Integer>();
    for (int n : nums) {
        map.put(n, map.getOrDefault(n, 0)+1);
    }
    int count = 0;
    for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
        if (k == 0) {
            if (entry.getValue() >= 2) {
                count++;
            } 
        } else {
            if (map.containsKey(entry.getKey()+k)) {
                count++;
            }
        }
    }
    return count; 
}

05 第四种解法

使用HashSet。使用两个HashSet,同样分为两种情况:k等于0和K不等于0。

如果k等于0时,对数组进行遍历,如果当前元素不存在于set1中,就添加进set1,如果存在set1中,就去判断是否存在于set2中,如果不存在,次数就加1,并将元素添加进set2中。

如果k不等于0,遍历数组,将当前元素添加进set1,将当前元素加上k后再添加进set2,然后使用retainAll方法,将set1中不包含set2元素的元素剔除掉(也就是两set的交集),最后count等于set1中元素的个数。

public int findPairs4(int[] nums, int k) {
    if (nums == null || nums.length == 0 || k < 0) {
        return 0;
    }
    Set<Integer> set1 = new HashSet<Integer>();
    Set<Integer> set2 = new HashSet<Integer>();
    int count = 0;
    if (k == 0) {
        for (int n : nums) {
            if (!set1.contains(n)) {
                set1.add(n);
            } else {
                if (!set2.contains(n)){
                    count++;
                }
                set2.add(n);
            }
        }
    } else {
        for (int n : nums) {
            set1.add(n);
            set2.add(n + k);
        }
        set1.retainAll(set2);
        count = set1.size();
    }
    return count;
}

06 第五种解法

使用双指针。还是先将数据排序,定义左右两个指针,分别从0开始,如果左右指针相等,说明是循环的第一次或者重复了,就需要将右指针往后移动一位。如果左指针所指向元素加上k后等于右指针的元素,那么次数加1,接着要判断,如果右指针所指向位置后面的元素和当前元素相等,那么右指针继续往后移动。如果左指针所指向元素加上k后小于右指针的元素,说明左边的元素小了,左指针向前移动。如果左指针所指向元素加上k后大于右指针的元素,说明右边的元素小了,右指针向前移动。

此解法的时间复杂度是O(n log(n)),空间复杂度是O(1)。

public int findPairs5(int[] nums, int k) {
    if (nums == null || nums.length == 0 || k < 0) {
        return 0;
    }
    Arrays.sort(nums);
    int count = 0;
    int start = 0, end = 0;
    while (end < nums.length) {
        if (start == end) {
            end++;
        } else if (nums[start] + k == nums[end]) {
            count++;
            while (end + 1 < nums.length && nums[end] == nums[end + 1]) {
                end++;
            }
            end++;
        } else if (nums[start] + k < nums[end]) {
            start++;
        } else if (nums[start] + k > nums[end]) {
            end++;
        }
    }
    return count;
}

07 小结

此题的测试用例中,k出现了负值,所以在特殊情况判断中,还需要判断k小于0,这也是本题不严谨的一个地方。

算法专题目前已日更超过三个月,算法题文章121+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

PyCharm + Anaconda虚拟环境:完美配置PySide6开发三件套(Designer/UIC/RCC)的避坑指南 本文详细介绍了如何在PyCharm和Anaconda虚拟环境中配置PySide6开发三件套(Designer/UIC/RCC),提供从环境准备到工具集成的完整解决方案。通过清晰的路径定位和PyCharm外部工具配置指南,帮助开发者快速搭建高效的Python GUI开发环境,避免常见配置陷阱。 阅读详情

相关推荐

OpenCV卡尺工具实战:5步搞定工业级圆与直线拟合(附完整C++源码)

本文详细介绍了使用OpenCV卡尺测量工具实现工业级圆与直线拟合的5个关键步骤,包括核心原理、环境配置、边缘点提取优化、鲁棒性几何拟合实现及QT集成技巧。通过模块化C++源码和实战案例,帮助开发者快速掌握高精度尺寸测量技术,适用于机械零件、PCB板等工业检测场景。

uran的专栏 842

LeetCode 1109 LeetCode 370 差分数组算法技巧

LeetCode370 区间加法思路分析使用差分数组的解题技巧差分数组:主要适用场景是频繁对原始数组的某个区间的元素进行增减;类似于前缀和构造的prefix数组,我们构造一个差分数组diff。diff[i] = nums[i] - nums[i - 1]示意图运用差分数组进行区间增删的操作若对nums[i…j]增(删) value :则diff[i] += value,即nums[i…]增加了value之后diff[j+1] -= value,即对nums[j…]减少了value,综合起来就是没有变化返回结

weixin_45687795的博客 340

EPSON RX8010SJ RTC实战:I2C寄存器配置避坑指南(附完整初始化代码)

本文详细解析了EPSON RX8010SJ RTC芯片在I2C寄存器配置中的常见问题与解决方案,包括TEST位、STOP位和中断控制等关键配置要点。通过实战经验分享和完整的初始化代码模板,帮助开发者避免常见陷阱,确保RTC模块的稳定运行。

weixin_28678831的博客 406

leetcode (K-diff Pairs in an Array)

Title:K-diff Pairs in an Array    532 Difficulty:Easy 原题leetcode地址:https://leetcode.com/problems/k-diff-pairs-in-an-array/   1. 首先排序,然后嵌套循环遍历数组,注意(a.如果找到一对,就跳出本次循环(内循环),b.跳过重复的数) 时间复杂度:O(n^2),两层循...

hsx1612727380的专栏 186

Howland电流源电路:从理论到实践的深度解析与优化策略

本文深度解析了Howland电流源电路的工作原理,从经典四电阻架构的“虚短”“虚断”分析,到其实现宽带恒流输出的理论优势。重点剖析了实践中因电阻精度、运放参数及PCB布局导致的性能瓶颈,并提供了引入第五电阻、优化运放选型等关键优化策略,旨在将输出阻抗从kΩ级提升至MΩ级,以满足精密测量与传感器驱动等应用需求。

weixin_29243063的博客 441

QGis二次开发 —— 1.1、ubuntu24.04下搭建QGis3.40.12二次开发环境(附:全部问题解决方法)

QGis二次开发 —— 1.1、ubuntu24.02下搭建QGis3.40.12二次开发环境(附:全部问题解决方法)

251

C语言基础 时间复杂度和空间复杂度

---------------start reading--------------- 时间复杂度 定义 时间复杂度:运行次数与规模之间的函数关系 O(f(n)),又叫大O阶 举例 int main() { int i; int n=10; int temp=0; for(i=1;i&amp;lt;=n;i++) { temp+=i; } return 0; } 运行次数:1,2,...

kira_981019的博客 6709

六、Tool 工具系统:让大模型拥有“手脚“

我问你一个问题:大模型能不能告诉你"北京今天天气怎么样"?能——它能用非常流畅的中文回答你不能——它不知道这个答案因为它没有联网能力,也没有实时数据。它可能会自信地编一个"今天晴,25 度"给你——这就是幻觉。问题出在哪?大模型是一个"推理引擎",不是一个"执行引擎"。它知道天气 API 怎么调用,但不能真的发出 HTTP 请求。它知道 Python 代码怎么写,但不能真的运行代码。它知道数学公式,但做不了精确的大数计算。Tool 工具系统解决的,就是这个"最后一公里"问题。

牛肉胡辣汤 157

数据结构:C语言实现数组逆序,空间复杂度为O(1)

思路 计算数组长度 第一个与倒数第一个互换位置;第i个位置与第length-1-i个位置互换 循环数组一半位置即可 以下为代码,可直接运行: #include <stdio.h> int main() { int l[10] = {10,9,8,7,6,5,4,3,2,1}; int temp,position; int length =sizeof(l)/sizeof(int); printf("This length of array = %d\n",length); fo

布尔没有码 1096

社交媒体文章内容与评论抓取:Python 爬虫实战教程

通过本文的介绍,我们学习了如何使用 Python 编写爬虫,抓取社交媒体平台的文章内容和评论。我们详细介绍了如何使用requestsSelenium和Tweepy等工具,抓取微博和 Twitter 上的公开数据。同时,我们还讨论了如何处理反爬虫机制,避免账号或 IP 被封禁。抓取社交媒体数据是一个充满挑战和乐趣的过程,掌握这些技术后,你可以在大数据分析、情感分析和舆情监测等方面得到更深层次的应用。

2201_76125261的博客 1710

以太网_RGMII接口与GMII接口的转化_03

RGMII接口转GMII接口!

weixin_42499230的博客 378

k匿名java实现_LeetCode算法题-K-diff Pairs in an Array(Java实现)

这是悦乐书的第254次更新,第267篇原创01 看题和准备今天介绍的是LeetCode算法题中Easy级别的第121题(顺位题号是532)。给定一个整数数组和一个整数k,您需要找到数组中唯一的k-diff对的数量。 这里k-diff对被定义为整数对(i,j),其中i和j都是数组中的数字,它们的绝对差是k。例如:输入:[3,1,4,1,5],k = 2输出:2说明:数组中有两个2-diff对,(1,...

weixin_29266007的博客 671

解决pd.read_json报错ValueError: Trailing data问题

首先,我们使用open函数打开JSON文件,然后使用json.load函数将JSON文件数据解码为Python对象。在使用Python进行数据处理中,我们经常需要将JSON格式的数据读入到DataFrame中进行处理。而使用pandas库的read_json函数,就可以方便地将JSON数据读入到DataFrame中。但是有时候在读取JSON数据时,会遇到一个非常常见的错误:ValueError: Trailing data。这个错误的解决方案并不难,只需要在read_json中添加一个参数即可。

学习使你进步。 2234

leetcode解题之532. K-diff Pairs in an Array Java版

leetcode解题之532. K-diff Pairs in an Array Java版

mine_song的博客 1862

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

【leetcode】532. K-diff Pairs in an Array

532. K-diff Pairs in an Arrayhttps://leetcode.com/problems/k-diff-pairs-in-an-array/#/description Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in th

xxxxzr的博客 883

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Leetcode——532. K-diff Pairs in an Array

题目原址 https://leetcode.com/problems/k-diff-pairs-in-an-array/description/ 题目描述 Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a ...

想当厨子的程序媛 299

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

532. K-diff Pairs in an Array

Problem Description: Given an array of integers and an integerk, you need to find the number ofuniquek-diff pairs in the array. Here ak-diffpair is defined as an integer pair (i, j), whereian...

zzyy17的专栏 188

Leetcode 532 K-diff Pairs in an Array

Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers

夜色之浓,莫过于黎明前的黑暗。 403

leetcode532. K-diff Pairs in an Array

532. K-diff Pairs in an ArrayGiven an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where

rxt2012kc的博客 355

K-diff Pairs in an Array

题目地址:https://leetcode.com/problems/k-diff-pairs-in-an-array/#/descriptionGiven an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair

K.Sun 484

[LeetCode]532. K-diff Pairs in an Array

https://leetcode.com/problems/k-diff-pairs-in-an-array/#/description 找出绝对值差距为k的unique的对的数目 用HashMap保存num以及出现次数。然后遍历map而不是nums!!注意k为0的情况。 public class Solution { pu

gqk289的专栏 602

leetcode532~K-diff Pairs in an Array

Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in

stone_yw的博客 1785

leetcode 532. K-diff Pairs in an Array

记录一下这道无聊的题: class Solution { public int findPairs(int[] nums, int k) { HashMap<Integer,Integer> map = new HashMap<>(); for(int num : nums){ map.put(num,map....

xiaobailaji的博客 105

LeetCode-532:K-diff Pairs in an Array (给定绝对值差的值对个数)

给定数组,找出所有差的绝对值为k的元素值对(i, j),返回元素值对的数量

大树先生的博客 1506

[Leetcode]532. K-diff Pairs in an Array

题目大意:点击打开链接 public int findPairs(int[] nums, int k) { if(nums==null||nums.length==0||k<0){ return 0; } Map map=new HashMap(); for(int i:nums){ map.put(i,map.getOr

offerkkl的博客 517

LeetCode K-diff Pairs in an Array

原题链接在这里:https://leetcode.com/problems/k-diff-pairs-in-an-array/#/description 题目: Given an array of integers and an integerk, you need to find the number ofuniquek-diff pairs in the array. Here a...

weixin_30667649的博客 123
上一篇: LeetCode算法题-Minimum Absolute Difference in BST(Java实现)
下一篇: LeetCode算法题-Convert BST to Greater Tree(Java实现)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值