zoukankan      html  css  js  c++  java
  • Contains Duplicate III

    题目描写叙述:


    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.


    就是给定1个数组nums,以及索引最大间隔k,和值最大间隔t。在nums数组内,找出是否存在num[i],和nums[j],当中i,j ∈[0,nums.Length-1]。使得 abs(i-j) <= k 而且 abs(nums[i]-nums[j]) <= t


    思路:
    1. 遍历nums数组,使用BST来存nums[i]在k范围内全部可达的数
    2. 使用SortedSet<T>这个数据结构来存放从i到k范围内的每一个数,因为SortedSet的内部实现是平衡树
    (http://stackoverflow.com/questions/3262947/is-there-a-built-in-binary-search-tree-in-net-4-0)。因此它的增删查都是log(n),所以算上外循环,整体复杂度是n*log(n)
    3. 确定要查找的边界:
    min = nums[i] - t; // 可取的最小值
    max = nums[i] + t; // 可取的最大值


    4. 假设sortedSet的长度大于 k。删除第一个。仅仅须要维护长度为k的数据就能够了




    实现代码:







    public class Solution {
        public bool ContainsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        	if(k < 1 || t < 0){
    			return false;
    		}
    		
    		if(nums == null || nums.Length == 1)
        	{
        		return false;
        	}
    		
    		var map = new SortedSet<int>();
    		
            for(var i = 0 ;i < nums.Length; i++)
    		{
    		    if(nums[i] > Int32.MaxValue){
    				return false;
    			}
    			
    			if(map.Count > k){
    				map.Remove(nums[i-k-1]);
    			}
    			
    			var max = nums[i] + t;
    			if(nums[i] > 0 && max < 0){
    				max = Int32.MaxValue;
    			}
    			
    			var min = nums[i] - t;
    			
    			var found = map.GetViewBetween(min,max);
    			if(found.Count > 0){
    				return true;
    			}
    
    
    			map.Add(nums[i]);
           }
    	   
           return false;
        }
    }


  • 相关阅读:
    把csv文件导入数据库
    c# DataTable 针对xml、excel、csv导入和导出
    ASP.NET常用珍藏代码
    C# 判断图片链接是否存在
    在asp.net中长内容自动分页的实现.NET教程
    SQL代理服务启动不了SQLSERVERAGENT
    SQL重复记录查询(转载)
    在asp.net中长内容自动分页的实现.NET教程2
    根据年月来判断月里天数
    SQL字符串函数
  • 原文地址:https://www.cnblogs.com/clnchanpin/p/6912482.html
Copyright © 2011-2022 走看看