【LeetCode-面试算法经典-Java实现】【219-Contains Duplicate II(包含重复元素II)】

来源:互联网 发布:jre windows i586.exe 编辑:程序博客网 时间:2024/06/05 06:35

【219-Contains Duplicate II(包含重复元素II)】


【LeetCode-面试算法经典-Java实现】【所有题目目录索引】


代码下载【https://github.com/Wang-Jun-Chao】

原题

  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.

题目大意

  给定一个整数数组nums与一个整数k,当且仅当存在两个不同的下标i和j满足nums[i] = nums[j]并且|i-j|<=k时返回true,否则返回false。

解题思路

  对nums[0…n-1],存入一个map中,(muns[i], i),如果键nums[k]已经存在,则比较之前的下标和现在的下标的差值,如果差值不大于k,说明到了满足条件的两个值,否则使用新的下标作为值

代码实现

算法实现类

import java.util.HashMap;import java.util.Map;public class Solution {    public boolean containsNearbyDuplicate(int[] nums, int k) {        // 输入条件判断        if (nums == null || nums.length < 2 || k < 1) {            return false;        }        Map<Integer, Integer> map = new HashMap<>();        for (int i = 0; i < nums.length; i++) {            // 如果没有对应的key添加进去            if (!map.containsKey(nums[i])) {                map.put(nums[i], i);            }            // 已经有对应的key-value对            else {                // 原来保存的值对应的下标,它一定小于现在的下标                int value = map.get(nums[i]);                if (i - value <= k) {                    return true;                }                map.put(nums[i], i);            }        }        return false;    }}

评测结果

  点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。

这里写图片描述

特别说明

欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/48084061】

2 0
原创粉丝点击