力扣题解: 00217 & 00219

117 阅读1分钟
原文链接: mp.weixin.qq.com

00217 存在重复元素

题目描述

给定一个整数数组,判断是否存在重复元素。

如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。

示例 1:

    输入: [1,2,3,1]

    输出: true

示例 2:

    输入: [1,2,3,4]

    输出: false

示例 3:

    输入: [1,1,1,3,3,4,3,2,4,2]

    输出: true

力扣地址

  • https://leetcode.com/problems/contains-duplicate/

  • https://leetcode-cn.com/problems/contains-duplicate/

解题报告

本题解由微信公众号 小猿刷题提供, 错误之处, 欢迎指正.

使用散列表判断是否存在或者去重判断总长度都可以

  • 遍历过程中判断

    public boolean containsDuplicate(int[] nums) {

    Set<Integer> set = new HashSet<>(nums.length);

    for (int x: nums) {

    if (set.contains(x)) {

    return true;

    }

    set.add(x);

    }

    return false;

    }

  • 遍历完成后判断

    /**

    * 微信公众号"小猿刷题"

    */

    public boolean containsDuplicate(int[] nums) {

    Set<Integer> set = new HashSet();

    for(int i = 0; i < nums.length; i ++){

    set.add(nums[i]);

    }

    return set.size() != nums.length;

    }

00219 存在重复元素 II

题目描述

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

力扣地址

  • https://leetcode.com/problems/contains-duplicate-ii/

  • https://leetcode-cn.com/problems/contains-duplicate-ii/

解题报告

本题解由微信公众号 小猿刷题提供, 错误之处, 欢迎指正.

    /**

    * 微信公众号"小猿刷题"

    */

    public boolean containsNearbyDuplicate(int[] nums, int k) {

    Map<Integer, Integer> map = new HashMap<Integer, Integer>();

    for (int i = 0; i < nums.length; i++) {

    if (map.containsKey(nums[i])) {

    if (i - map.get(nums[i]) <= k) {

    return true;

    }

    }

    map.put(nums[i], i);

    }

    return false;

    }