是否包含重复元素2

来源:互联网 发布:薛之谦女装品牌淘宝店 编辑:程序博客网 时间:2024/06/03 17:42

219. Contains Duplicate II

 

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.

大概意思就是一个整数数组,和一个整数k,数组中有两个下标不同 i 和j ,但是值却相同nums[i]=nums[j];i 和 j 之间的差小于等于k。

如果存在这样的两个元素返回true。如果不存在返回false

public class Solution {    public boolean containsNearbyDuplicate(int[] nums, int k) {        Map<Integer, Integer> map = new HashMap<Integer, Integer>();    for (int i = 0; i < nums.length; i++) {map.put(nums[i], i);if (map.size() < i+1) {//map集合元素个数小于存入的个数,说明有重复值for (int j = 0; j < i; j++) {//遍历重复值之前的数组,找到下标if (nums[j] == nums[i]) {if (i-j <= k) {//比较两个相同元素的下标与k的大小关系return true;}}}}    }    return false;    }}


0 0
原创粉丝点击