LeetCode:Contains Duplicate II - 判断数组内是否有重复元素2

一、题目名称java

Contains Duplicate II(判断数组内是否有重复元素2)数组

二、题目地址函数

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

三、题目内容code

英文: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 difference between i and j is at most k.blog

中文:给出一个整数数组,判断该数组内是否有两个元素值是相同的,且他们的索引值相差不大于k,是则返回true,不然返回false索引

四、一个TLE的方法leetcode

本题若是直接使用暴力方法解决会运行超时。一段TLE的Java代码以下:开发

/**
 * @功能说明:LeetCode 219 - Contains Duplicate II
 * @开发人员:Tsybius2014
 * @开发时间:2015年10月15日
 */
public class Solution {
    
    /**
     * 查看数组内是否有重复元素且相邻重复元素索引间隔不大于K
     * @param nums
     * @return
     */
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        
        if (nums.length <= 1) {
            return false;
        }

        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j <= i + k && j < nums.length; j++) {
                if (nums[i] == nums[j]) {
                    return true;
                }
            }
        }
        
        return false;
    }
}

五、解题方法1rem

一个比较容易想到的方式是使用HashMap来完成目标,使用HashMap解决本题的方式与解决第217题的方式(Contains Duplicate)很是相似。

Java代码以下:

import java.util.HashMap;

/**
 * @功能说明:LeetCode 219 - Contains Duplicate II
 * @开发人员:Tsybius2014
 * @开发时间:2015年10月15日
 */
public class Solution {
    
    /**
     * 查看数组内是否有重复元素且相邻重复元素索引间隔不大于K
     * @param nums
     * @return
     */
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        
        if (nums.length <= 1) {
            return false;
        }

        HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
        
        for (int i = 0; i < nums.length; i++) {
            if (hashMap.containsKey(nums[i]) && i - hashMap.get(nums[i]) <= k) {
                return true;
            }
            hashMap.put(nums[i], i);
        }
        
        return false;
    }
}

六、解题方法2

另外一种方式是使用HashSet来解决本问题。HashSet是使用HashMap实现的集合。在HashSet的add函数中,若是被插入的元素已存在,则返回true,不然返回false。下面的Java代码就是利用了HashSet的这个性质:

import java.util.HashSet;

/**
 * @功能说明:LeetCode 219 - Contains Duplicate II
 * @开发人员:Tsybius2014
 * @开发时间:2015年10月15日
 */
public class Solution {

    /**
     * 查看数组内是否有重复元素且相邻重复元素索引间隔不大于K
     * 
     * @param nums
     * @return
     */
    public boolean containsNearbyDuplicate(int[] nums, int k) {

        if (nums.length <= 1) {
            return false;
        }

        HashSet<Integer> hashSet = new HashSet<Integer>();
        for (int i = 0; i < nums.length; i++) {
            if (i > k) {
                hashSet.remove(nums[i - k - 1]);
            }
            if (!hashSet.add(nums[i])) {
                return true;
            }
        }

        return false;
    }
}

END

相关文章
相关标签/搜索