算法题——Maximum Gap(JAVA)基数排序
来源:互联网 发布:cf手游尼泊尔战龙 数据 编辑:程序博客网 时间:2024/06/05 22:49
题目描述:
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Try to solve it in linear time/space.
Return 0 if the array contains less than 2 elements.
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
读题:
求出数组排序后相连两个数之间最大的差值。题目要求讲的很清楚了,要求线性复杂度,非负整数,不超过32位。即要求用基数排序完成。
知识储备:
基数排序
基数排序的主要思路是,将所有待比较数值(必须是正整数)统一为同样的数位长度,数位较短的数前面补零. 然后, 从最低位开始, 依次进行一次稳定排序(常用计数排序算法)
为什么同一数位的排序子程序要使用稳定排序?
稳定排序能保证,上一次的排序成果被保留,十位数的排序过程能保留个位数的排序成果,百位数的排序过程能保留十位数的排序成果。
这个算法的难度在于分离数位,将分离出的数位代表原元素的代表, 用作计数排序.但是分离数位不能脱离原来的数字,计数排序的结果,还是要移动原元素.
解题思路:
1.每个数字的从低位开始的每一位进行比较,直至最高位;
2.用计数排序算法,比较位若为1,则a[1]++,然后统计该位在此队列中的排序。
3.输出此次排序位的结果,将结果作为新的输入数组,开始下一趟的排序。
提交代码:
public class Solution { public int maximumGap(int[] nums) { if (nums.length < 2) { return 0; } nums = radixSort(nums, 10); int max = 0; for (int i = 1; i < nums.length; i++) { max = Math.max(max, nums[i]-nums[i-1]); } return max; } public int[] radixSort(int[] ArrayToSort, int digit) { //low to high digit for (int k = 1; k <= digit; k++) { //temp array to store the sort result inside digit int[] tmpArray = new int[ArrayToSort.length]; //temp array for countingsort int[] tmpCountingSortArray = new int[10]; //CountingSort for (int i = 0; i < ArrayToSort.length; i++) { //split the specified digit from the element int tmpSplitDigit = ArrayToSort[i]/(int)Math.pow(10,k-1) - (ArrayToSort[i]/(int)Math.pow(10,k))*10; tmpCountingSortArray[tmpSplitDigit] += 1; } for (int m = 1; m < 10; m++) { tmpCountingSortArray[m] += tmpCountingSortArray[m - 1]; } //output the value to result for (int n = ArrayToSort.length - 1; n >= 0; n--) { int tmpSplitDigit = ArrayToSort[n] / (int)Math.pow(10,k - 1) - (ArrayToSort[n]/(int)Math.pow(10,k)) * 10; tmpArray[tmpCountingSortArray[tmpSplitDigit]-1] = ArrayToSort[n]; tmpCountingSortArray[tmpSplitDigit] -= 1; } //copy the digit-inside sort result to source array for (int p = 0; p < ArrayToSort.length; p++) { ArrayToSort[p] = tmpArray[p]; } } return ArrayToSort; }}
- 算法题——Maximum Gap(JAVA)基数排序
- Algorithms—164.Maximum Gap
- 基数排序 leetcode oj 164. Maximum Gap
- Java-Maximum Gap
- Maximum Gap (Java)
- 由Maximum Gap,谈桶排序,基数排序和计数排序
- LeetCode – Maximum Gap (Java)
- Java排序算法总结之(五)—— 基数排序
- 排序算法之——基数排序(Java实现)
- 排序算法之——基数排序(Java实现)
- [Leetcode新题] Maximum Gap
- LeetCode(164)Maximum Gap
- 排序相关—— 相邻两数的最大差值( Maximum Gap-LeetCode)
- Maximum Gap
- Maximum Gap
- Maximum Gap
- MAXIMUM GAP
- Maximum Gap
- 小知识点
- Java裸体小白的多态
- 英飞凌磁传感器 TLE5012b STM32F103 SPI 程序说明
- Servlet 点击计数器
- git仓库迁移
- 算法题——Maximum Gap(JAVA)基数排序
- 模拟实现myshell
- 1001. 害死人不偿命的(3n+1)猜想 (15)
- 《CUDA并行程序设计-GPU编程指南》读书笔记--(2)CUDA内存处理
- Windows下eclipse上安装hadoop插件,编写mapreduce 程序
- 默认表空间+查询默认表空间+设置默认表空间
- 1002. 写出这个数 (20)
- nginx,php-fpm的安装配置
- 1004. 成绩排名 (20)