admin管理员组

文章数量:1031255

哈希表系列一>存在重复元素II && 存在重复元素I

题目:

链接: link

这里是引用

链接: link

解析:

存在重复元素 II–>代码:

代码语言:javascript代码运行次数:0运行复制
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer,Integer> hash = new HashMap<>();//<nums[i],i>
        for(int i = 0; i < nums.length; i++){

            if(hash.containsKey(nums[i])){
               if(i - hash.get(nums[i]) <= k) return true; 
            }
            hash.put(nums[i],i);
        }
        return false;
    }
}

存在重复元素–>代码:

代码语言:javascript代码运行次数:0运行复制
class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> hash = new HashSet<>();
        for(Integer x : nums){
            if(hash.contains(x))
                return true;
            hash.add(x);    
        }
        return false;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2025-04-12,如有侵权请联系 cloudcommunity@tencent 删除hashintintegerreturnclass

哈希表系列一>存在重复元素II && 存在重复元素I

题目:

链接: link

这里是引用

链接: link

解析:

存在重复元素 II–>代码:

代码语言:javascript代码运行次数:0运行复制
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer,Integer> hash = new HashMap<>();//<nums[i],i>
        for(int i = 0; i < nums.length; i++){

            if(hash.containsKey(nums[i])){
               if(i - hash.get(nums[i]) <= k) return true; 
            }
            hash.put(nums[i],i);
        }
        return false;
    }
}

存在重复元素–>代码:

代码语言:javascript代码运行次数:0运行复制
class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> hash = new HashSet<>();
        for(Integer x : nums){
            if(hash.contains(x))
                return true;
            hash.add(x);    
        }
        return false;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2025-04-12,如有侵权请联系 cloudcommunity@tencent 删除hashintintegerreturnclass

本文标签: 哈希表系列一>存在重复元素II ampamp 存在重复元素I