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();
    	}
    }
    
  • 相关阅读:
    Typora使用腾讯云图床
    2020年8月总结
    113 路径之和II
    103 二叉树的锯齿形层次遍历
    128 最长连续序列
    160 相交链表
    33 搜索旋转排序数组
    学习制作GitHub徽标
    105 从前序与中序遍历序列构造二叉树
    重新封装了layer.tips,自定义跟随弹窗
  • 原文地址:https://www.cnblogs.com/aoximin/p/12525850.html
Copyright © 2011-2022 走看看