LeetCode Contains Duplicate II

原创 2015年07月09日 17:04:36

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;
	}
}


【leetcode】219. Contains Duplicate II

一、题目描述 Given an array of integers and an integer k, find out whether there are two distinct indic...

LeetCode | Contains Duplicate II

Given an array of integers and an integer k, find out whether there there are two distinct indices ...

LeetCode笔记:219. Contains Duplicate II

判断一个数组中一定范围内是否有相同的数字

【Leetcode Algorithm】Contains Duplicate II

Given an array of integers and an integer k, find out whether there there are two distinct indices...

leetcode笔记--Contains Duplicate I & II & III

Contains Duplicate 题目:难度(Easy) Given an array of integers, find if the array contains any duplicat...

Leetcode:219. Contains Duplicate II(数组是否含有重复元素)

Given an array of integers and an integer k, find out whether there are two distinct indices i and j...

leetcode之Contains Duplicate II 问题

问题描述: Given an array of integers and an integer k, find out whether there are two distinct indicesi...

leetcode: (219) Contains Duplicate II

【Question】 Given an array of integers and an integer k, find out whether there are two distinct ind...
  • zk031
  • zk031
  • 2015年08月28日 20:50
  • 193

LeetCode 之 Contains Duplicate I II III — C++ 实现

Contains Duplicate   Given an array of integers, find if the array contains any duplicates. Your fu...

Leetcode 219. Contains Duplicate II

Given an array of integers and an integer k, find out whether there are two distinct indices i and j...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode Contains Duplicate II
举报原因:
原因补充:

(最多只允许输入30个字)