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的簡(jiǎn)單解法
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/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...
摘要:和唯一的不同是組合中不能存在重復(fù)的元素,因此,在遞歸時(shí)將初始位即可。 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...
摘要:整個(gè)過(guò)程相當(dāng)于,直接在和里去掉既是又是的。所以最后返回的,一定是只出現(xiàn)過(guò)一次的,而出現(xiàn)兩次的都在里,出現(xiàn)三次的都被消去了。 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...
閱讀 1019·2022-07-19 10:19
閱讀 1794·2021-09-02 15:15
閱讀 1007·2019-08-30 15:53
閱讀 2653·2019-08-30 13:45
閱讀 2652·2019-08-26 13:57
閱讀 1983·2019-08-26 12:13
閱讀 1006·2019-08-26 10:55
閱讀 545·2019-08-26 10:46