博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode之旅】 数组 - 219. 存在重复元素II
阅读量:2056 次
发布时间:2019-04-28

本文共 1598 字,大约阅读时间需要 5 分钟。

给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k

示例 1:

输入: nums = [1,2,3,1], k = 3输出: true

示例 2:

输入: nums = [1,0,1,1], k = 1输出: true

示例 3:

输入: nums = [1,2,3,1,2,3], k = 2输出: false

解答:

/** * 回溯:先两两对比,然后如果后一个大于前一个,则跳出内层循环,继续比较, * 相等的话就判断i - j <= k,移除与k对应的之前的数 * 小于的话,就将j的索引往前移,继续判断 * @param nums * @param k * @return */public static boolean containsNearbyDuplicate1(int[] nums, int k) {    for (int i = 1; i < nums.length; i++) {        for (int j = i - 1; j >= 0; j--) {            if (nums[i] > nums[j]){                break;            }else if (nums[i] == nums[j]){                if (i - j <= k){                    return true;                }            }        }    }    return false;}/** * 使用Set集合 * @param nums * @param k * @return */public static boolean containsNearbyDuplicate2(int[] nums, int k){    Set
set = new HashSet<>(); for (int i = 0; i < nums.length; i++) { //移除距离比k远的元素 if (i > k){ set.remove(nums[i - k - 1]); } //因为所有仍存在的元素的距离都满足最大距离为k, // 如果这时存在相同元素则返回true,反之为false if (!set.add(nums[i])){ return true; } } return false;}/** * 使用Map集合 * @param nums * @param k * @return */public static boolean containsNearbyDuplicate3(int[] nums, int k) { Map
indices = new HashMap<>(); for (int i = 0; i < nums.length; i++) { //利用map的特性,如果put已经存在的key,则会返回上一个key的值 //如果不存在,则返回null Integer lastIndex = indices.put(nums[i], i); if (lastIndex != null && (i - lastIndex) <= k) return true; } return false;}

 

转载地址:http://rtslf.baihongyu.com/

你可能感兴趣的文章
稻草人手记
查看>>
第一次kaggle比赛 回顾篇
查看>>
leetcode 50. Pow(x, n)
查看>>
leetcode 130. Surrounded Regions
查看>>
【托业】【全真题库】TEST2-语法题
查看>>
博客文格式优化
查看>>
【托业】【新托业全真模拟】疑难语法题知识点总结(01~05)
查看>>
【SQL】group by 和order by 的区别。
查看>>
【F12】谷歌浏览器--前台效果可以在不访问服务器的前提下直接改样式看效果是否是预期值。...
查看>>
【Python】详解Python多线程Selenium跨浏览器测试
查看>>
Jmeter之参数化
查看>>
Shell 和Python的区别。
查看>>
Python 列表(list)、字典(dict)、字符串(string)常用基本操作小结
查看>>
Loadrunner之https协议录制回放报错如何解决?(九)
查看>>
python中xrange和range的异同
查看>>
列表、元组、集合、字典
查看>>
【Python】easygui小甲鱼
查看>>
【Python】关于Python多线程的一篇文章转载
查看>>
【Pyton】【小甲鱼】文件
查看>>
【Pyton】【小甲鱼】永久存储:腌制一缸美味的泡菜
查看>>