LeetCode Contains Duplicate II

来源:互联网 发布:第三方网络支付平台 编辑:程序博客网 时间:2024/05/15 07:38

Description:

Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.

Solution:

把TreeMap的<key,value>对存储的分别是nums[i]和i,表示等于nums[i]的最近的index,如果最近的index和当前的i之差小于等于k,则返回true。在线处理即可。

import java.util.*;public class Solution {public boolean containsNearbyDuplicate(int[] nums, int k) {TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();int prePosition;for (int i = 0; i < nums.length; i++) {if (map.containsKey(nums[i])) {prePosition = map.get(nums[i]);if (i - prePosition <= k)return true;}map.put(nums[i], i);}return false;}}


0 0
原创粉丝点击