• 无序数组在排序后的最大相邻查


    前言

    原理后续补齐

    代码

    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();
    	}
    }
    
  • 相关阅读:
    假期周总结七
    假期周总结六
    假期周总结五
    假期周总结四
    假期周总结三
    假期总结二
    假期周总结一
    项目目标分析
    lightoj 1013
    lightoj 1012
  • 原文地址:https://www.cnblogs.com/aoximin/p/12525850.html
Copyright © 2020-2023  润新知