Problem
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
ExampleGiven nums = [1,2,1], k = 0, return false.
Solutionpublic class Solution { /** * @param nums: the given array * @param k: the given number * @return: whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k */ public boolean containsNearbyDuplicate(int[] nums, int k) { // Write your code here if (nums.length < 2 || k < 1) return false; Setset = new HashSet<>(); for (int i = 0; i < nums.length; i++) { // i - (i-k-1) > k if (i > k) set.remove(nums[i-k-1]); if (set.contains(nums[i])) return true; set.add(nums[i]); } return false; } }
也可以用HashMap的简单解法
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/76465.html
Subsets Problem Given a set of distinct integers, return all possible subsets. Notice Elements in a subset must be in non-descending order.The solution set must not contain duplicate subsets. Example ...
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 dif...
摘要:和唯一的不同是组合中不能存在重复的元素,因此,在递归时将初始位即可。 Combination Sum I Problem Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T...
Problem Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical...
摘要:整个过程相当于,直接在和里去掉既是又是的。所以最后返回的,一定是只出现过一次的,而出现两次的都在里,出现三次的都被消去了。 Single Number I Problem Given 2*n + 1 numbers, every numbers occurs twice except one, find it. Example Given [1,2,2,1,3,4,3], return...
阅读 999·2022-07-19 10:19
阅读 1772·2021-09-02 15:15
阅读 992·2019-08-30 15:53
阅读 2632·2019-08-30 13:45
阅读 2619·2019-08-26 13:57
阅读 1962·2019-08-26 12:13
阅读 985·2019-08-26 10:55
阅读 523·2019-08-26 10:46