379.Reorder array to construct the minimum number-将数组重新排序以构造最小值(中等题)
来源:互联网 发布:服务器端口怎么关闭 编辑:程序博客网 时间:2024/04/30 17:58
将数组重新排序以构造最小值
题目
给定一个整数数组,请将其重新排序,以构造最小值。
样例
给定 [3, 32, 321],通过将数组重新排序,可构造 6 个可能性数字:
3+32+321=332321
3+321+32=332132
32+3+321=323321
32+321+3=323213
321+3+32=321332
321+32+3=321323
其中,最小值为 321323,所以,将数组重新排序后,该数组变为 [321, 32, 3]。挑战
在原数组上完成,不使用额外空间。
题解
本题类似于184.Largest Number-最大数(中等题),是求最小数。但是由于题目要求不能使用额外空间,则需要我们自己实现排序算法(这里使用的是快排算法),元素大小比较可参见184题。
public class Solution { /** * @param nums n non-negative integer array * @return a string */ public String minNumber(int[] nums) { StringBuilder sb = new StringBuilder(); quickSort(nums,0,nums.length-1); for (int i=0;i<nums.length;i++) { if (sb.length() == 0 && nums[i] == 0) { continue; } sb.append(String.valueOf(nums[i])); } return sb.length() == 0 ? "0" : sb.toString(); } private int compare(int o1, int o2) { return (String.valueOf(o1)+String.valueOf(o2)).compareTo(String.valueOf(o2)+String.valueOf(o1)); } private void quickSort(int[] a, int left, int right) { if (left < right) { int temp = a[left]; int i = left; int j = right; while (i < j) { while (j > i && compare(a[j],temp) >=0) { j--; } while (i < j && compare(a[i],temp) <= 0) { i++; } if (i < j) { swap(a, i, j); } } swap(a, left, j); quickSort(a,left,i-1); quickSort(a, i+1, right); } } private void swap(int[] a, int i, int j) { int temp = a[j]; a[j] = a[i]; a[i] = temp; }}
Last Update 2016.11.11
0 0
- 379.Reorder array to construct the minimum number-将数组重新排序以构造最小值(中等题)
- Reorder array to construct the minimum number
- #379 Reorder array to construct the minimum number
- [LintCode]Reorder array to construct the minimum number
- Reorder array to construct the minimum number 解题报告
- LintCode 379:Reorder array to construct the minimum number
- [LintCode]379.将数组重新排序以构造最小值
- 159.Find Minimum in Rotated Sorted Array-寻找旋转排序数组中的最小值(中等题)
- lintcode-将数组重新排序以构造最小值
- Lintcode 将数组重新排序以构造最小值
- lintcode[379]将数组重新排序以构造最小值
- lintcode(379)将数组重新排序以构造最小值
- LintCode:将数组重新排序以构造最小值
- LINTCODE——将数组重新排序以构造最小值
- 将数组重新排序以构造最小值-LintCode
- 160.Find Minimum in Rotated Sorted Array II-寻找旋转排序数组中的最小值 II(中等题)
- Find Minimum in Rotated Sorted Array (旋转数组最小值)
- 205.Interval Minimum Number-区间最小数(中等题)
- 实现只能同时一个人登陆管理后台
- git clone 时 提示 warn:..............: Filename too long
- 架构师之路
- 数组的概述,内存分配,两种数据类型的对比
- 第三个页面 移动端&PC端
- 379.Reorder array to construct the minimum number-将数组重新排序以构造最小值(中等题)
- echart2.0实现折线图转折点闪烁效果
- 解决Oracle 11g在用EXP导出时,空表不能导出的问题
- java https双向认证实现
- Mark!Android最佳的开源库集锦
- 5款常见原型工具,产品特色知多少?
- /*题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。 */
- The type org.springframework.dao.support.DaoSupport cannot be resolved. It is indirectly referenced
- 最长上升子序列题目大合集