zoukankan      html  css  js  c++  java
  • 无序数组在排序后的最大相邻查

    前言

    原理后续补齐

    代码

    public class Bucket
    {
    	public int? max { get; set; }
    
    	public int? min { get; set; }
    }
    class Program
    {
    
    	public static int getMaxSortedDistance(int[] array)
    	{
    		int max = array[0];
    		int min = array[0];
    		for (int i = 1; i < array.Length-1; i++)
    		{
    			if (array[i] > max)
    			{
    				max = array[i];
    			}
    
    			if (array[i] < min)
    			{
    				min = array[i];
    			}
    		}
    
    		var BucketNumber = array.Length;
    		double BucketAreaNumber =((double)(max - min)) / (BucketNumber-1);
    		Bucket[] buckets = new Bucket[BucketNumber];
    		for (int i = 0; i < buckets.Length; i++)
    		{
    			buckets[i] = new Bucket();
    		}
    		for (int i = 0; i < array.Length; i++)
    		{
    			int index=Convert.ToInt32((array[i] - min) / BucketAreaNumber);
    			var currentBucket=buckets[index];
    		   
    			if (currentBucket.max == null || currentBucket.max < array[i])
    			{
    				currentBucket.max = array[i];
    			}
    			
    
    			if (currentBucket.min==null||currentBucket.min > array[i])
    			{
    				currentBucket.min = array[i];
    			}
    		}
    		var MaxsortedDistance = 0;
    
    		for (int i=0;i< buckets.Length-1;i++)
    		{
    			if (buckets[i].max != null)
    			{
    				var constindex = i;
    				while(buckets[i + 1].min == null)
    				{
    					i++;
    				}
    				if ((buckets[i + 1].min - buckets[constindex].max) > MaxsortedDistance)
    				{
    					MaxsortedDistance = (int)(buckets[i + 1].min - buckets[constindex].max);
    				}
    			}
    		}
    		return MaxsortedDistance;
    	}
    
    	static void Main(string[] args)
    	{
    		int[] array = new int[] {2,9,5,10,6,50,21,31 };
    		Console.WriteLine(getMaxSortedDistance(array));
    		Console.ReadKey();
    	}
    }
    
  • 相关阅读:
    iptables的例子1
    Nginx教程
    bash编程基础
    centos7 PXE自动安装环境搭建
    矛盾破裂了
    20200823-矩阵的收尾与离散控制的跌跌撞撞
    20200817-三大公式的结束-频域法的再探
    markdown换行
    由二〇二〇新冠疫情引发的对于开源、分享这一理念的看法
    Windows简单使用记录
  • 原文地址:https://www.cnblogs.com/aoximin/p/12525850.html
Copyright © 2011-2022 走看看