LeetCode Contains Duplicate III

原创 2015年07月09日 19:46:24

Description:

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

Solution:

用一个数据结构,能够维护长度为K的列表,同时又有floor和ceiling功能即可。

这里是用TreeSet,也可以用SortedSet。

import java.util.*;

public class Solution {
	public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
		if (k < 1 || t < 0)
			return false;
		TreeSet<Integer> set = new TreeSet<Integer>();

		int n = nums.length;
		long number;
		for (int i = 0; i < n; i++) {
			if (set.floor((nums[i])) != null) {
				number = set.floor((nums[i]));
				if (number >= nums[i] - t)
					return true;
			}
			if (set.ceiling(nums[i]) != null) {
				number = set.ceiling(nums[i]);
				if (number <= nums[i] + t)
					return true;
			}

			set.add(nums[i]);
			if (i >= k) {
				set.remove(nums[i - k]);
			}
		}

		return false;
	}

	public static void main(String[] args) {
		Solution s = new Solution();
		System.out.println(s.containsNearbyAlmostDuplicate(new int[] { 2, 4 },
				1, 1));
	}
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

【leetcode题解】【再看一遍】【86】【M】Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array suc...

《leetCode》:Contains Duplicate III

题目Given an array of integers, find out whether there are two distinct indices i and j in the array s...

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

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

Leetcode220-Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array suc...

[Leetcode]Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array su...

[LeetCode] Contains Duplicate(II,III)

Contains DuplicateGiven an array of integers, find if the array contains any duplicates. Your functi...

leetcode笔记:Contains Duplicate III

题目大意是,给定一个整数数组,判断其中是否存在两个不同的下标i和j,满足:| nums[i] - nums[j] | <= t 且下标:| i - j | <= k。

[leetcode]Contains Duplicate III

昨天在leetcode上做了这道题,利用了C++中map存储结构的特征。 题意 Given an array of integers, find out whether there are tw...

Contains Duplicate III - LeetCode 220

题目描述: Given an array of integers, find out whether there are two distinct indices i and j in the ar...

[LeetCode] Contains Duplicate III

Contains Duplicate III Given an array of integers, find out whether there are two distinct indices ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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