LeetCode-219:Contains Duplicate II (一定范围内的两相同元素)

来源:互联网 发布:快速充电器软件下载 编辑:程序博客网 时间:2024/06/05 19:59

Question

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 absolute difference between i and j is at most k.

Idea

给定一个数组和一个整数 k,找出数组中是否存在两个不同的索引 i 和 j,使得 nums[i]=num[j],并且要求i和j之间的绝对差值小于等于 k.

  1. idea1:分析题目主要有两个要求,一个是找出数组中是否存在不同的i,j,有nums[i]=num[j],有则返回true;一个是要求i和j的绝对值差<=k。
    • nums[i]=num[j]的问题,可以利用HashSet来存储,因为HashSet中不存在重复的元素,一旦将重复元素添加如HashSet则操作会返回false;
    • |i-j|<=k的问题,可以利用滑动窗口的思想来解决,每次移动一个元素长度,当前在窗口中的元素添加入HashSet,不在窗口中的元素移出HashSet.

Code

idea1—Java

public class Solution {    public boolean containsNearbyDuplicate(int[] nums, int k) {        Set<Integer> set = new HashSet<Integer>();        for (int i=0; i<nums.length; i++){            if (i > k) set.remove(nums[i-k-1]);            if (!set.add(nums[i])) return true;        }        return false;    }}
  • 一旦元素的索引i大于制定的k,则每次循环需要将大于k个距离的索引元素移出HashSet,使用其remove()方法;
  • HashSet的add()方法,如果元素已经存在,则返回false;
  • Runtime:18ms,beats:68.49%.
  • 时间复杂度:O(n);空间复杂度:O(k)
原创粉丝点击