当前位置:网站首页>力扣 179、最大数
力扣 179、最大数
2022-06-27 05:49:00 【cqwoniu】
一、题目描述
给定一组非负整数 nums,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数。
注意:输出结果可能非常大,所以你需要返回一个字符串而不是整数。
二、思路描述
要解决这个题目是有一个技巧的,就是排序的条件和正常的不太一样。我们看给一个数组进行排序的时候,只需要比较两个元素 (假设 x 和 y 是数组的任意两个元素) 的大小即可:
只要 x > y,那么降序排列的话 y 就应该排在 x 的后面
只要 x < y,那么降序排列的话 x 就应该排在 y 的后面
对于这道题目,假设 x 和 y 是数组中任意两个元素,那么 x 是需要排在 y 的前面还是后面呢?这个取决于 xy 和 yx 哪个大哪个小:
如果 xy > yx,那么 y 应该排在 x 的后面
如果 xy < yx,那么 x 应该排在 y 的后面
比如,x = 30, y = 3,那么 xy = 303,yx = 330,因为 xy < yx ,所以 30 应该在排在 3 的后面,这样就可以得到最大值
三、代码
//179、最大数
public String largestNumber(int[] nums) {
// 排序
quickSort(nums,0,nums.length-1);
if(nums[0]==0)
return "0";
StringBuilder sb = new StringBuilder();
for(int num:nums){
sb.append(num);
}
return sb.toString();
}
public void quickSort(int[] nums, int l, int h) {
if (l >= h)
return;
int pivot = nums[h];
int less = l;
int great = h;
int i = l;
while (i <= great) {
String xy = nums[i] + "" + pivot;
String yx = pivot + "" + nums[i];
if (xy.compareTo(yx) > 0) {
swap(nums, i, less);
less++;
i++;
} else if (xy.compareTo(yx) < 0) {
swap(nums, i, great);
great--;
} else {
i++;
}
}
quickSort(nums,l,less-1);
quickSort(nums,great+1,h);
}
public void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
边栏推荐
- 30个单片机常见问题及解决办法!
- 开门小例子学习十种用例图
- 函数栈帧的形成与释放
- Create a basic WDM driver and use MFC to call the driver
- Discussion on streaming media protocol (MPEG2-TS, RTSP, RTP, RTCP, SDP, RTMP, HLS, HDS, HSS, mpeg-dash)
- QT using Valgrind to analyze memory leaks
- Netease cloud music params and encseckey parameter generation code
- Asp. Net core6 websocket simple case
- Win 10 如何打开环境变量窗口
- Add widget on qlistwidgetitem
猜你喜欢

Win 10 如何打开环境变量窗口

Open the door small example to learn ten use case diagrams

免费的 SSH 和 Telnet 客户端PuTTY

Implementation of easyexcel's function of merging cells with the same content and dynamic title

EasyExcel合并相同内容单元格及动态标题功能的实现

Basic concepts of neo4j graph database

Go日志-Uber开源库zap使用

Double position relay jdp-1440/dc110v

NLP-D62-nlp比赛D31&刷题D15

How JQ gets the reciprocal elements
随机推荐
Niuke practice 101-c reasoning clown - bit operation + thinking
IP网络通信的单播、组播和广播
Comprehensive application of OpenCV in contour detection and threshold processing
mysql 查询时将状态改为相对应的文字
Implementation of easyexcel's function of merging cells with the same content and dynamic title
LeetCode-515. 在每个树行中找最大值
C语言练手小项目(巩固加深知识点理解)
表单校验 v-model 绑定的变量,校验失效的解决方案
Wholestagecodegen of spark
Machunmei, the first edition of principles and applications of database... Compiled final review notes
Built in functions of spark
Logu p4683 [ioi2008] type printer problem solving
Qt使用Valgrind分析内存泄漏
30个单片机常见问题及解决办法!
洛谷P4683 [IOI2008] Type Printer 题解
[FPGA] design and implementation of frequency division and doubling based on FPGA
汇编语言-王爽 第13章 int指令-笔记
Create a basic WDM driver and use MFC to call the driver
Unity中跨平台获取系统音量
EasyExcel合并相同内容单元格及动态标题功能的实现