当前位置:网站首页>给出一个数组,如 [7864, 284, 347, 7732, 8498],现在需要将数组中的数字拼接起来,返回「最大的可能拼出的数字」
给出一个数组,如 [7864, 284, 347, 7732, 8498],现在需要将数组中的数字拼接起来,返回「最大的可能拼出的数字」
2022-07-07 21:52:00 【漁陽】
/** * 给出一个数组,如 [7864, 284, 347, 7732, 8498], * 现在需要将数组中的数字拼接起来,如按顺序依次拼接为:786428434777328498,数组中的数字拼接顺序可以任意, * 编写程序,返回「最大的可能拼出的数字」。(以上面数组为例,返回849878647732347284) * @param arrays * @return */
解题思路:拆解数组中的每一个数,将数值存放到栈中(明显的栈形数据结构);排序(用到了冒泡排序的思路) ,排序过程比较大小通过各数值之间的高位到低位的大小比较,比如8,70,按照这个排序8属于大者;最后将数组从后向前输出即完成拼接
public static String getMaxNum(long[] arrays) {
if (arrays == null || arrays.length == 0) {
return "0";
}
//存放所有拆解后的数据集
Map<Long, Stack<Integer>> numMaps = Maps.newHashMap();
for (long tn : arrays) {
long t = tn;
Stack<Integer> qu = new Stack<>();
do {
qu.push((int) t % 10);
t = t / 10;
} while (t > 0);
numMaps.put(tn, qu);
}
for (int i = 0; i < arrays.length; i++) {
for (int j = 0; j < arrays.length - i - 1; j++) {
Stack<Integer> f = numMaps.get(arrays[j]);
Stack<Integer> s = numMaps.get(arrays[j + 1]);
//比较大小
int fn = f.size() - 1;
int sn = s.size() - 1;
do {
if (f.get(fn) < s.get(sn)) {
break;
}
if (f.get(fn) > s.get(sn)) {
long tn = arrays[j];
arrays[j] = arrays[j + 1];
arrays[j + 1] = tn;
break;
}
fn--;
sn--;
} while (fn >= 0 && sn >= 0);
if (fn == -1 || sn == -1) {
fn = fn == -1 ? 0 : fn;
sn = sn == -1 ? 0 : sn;
if (f.get(fn) > s.get(sn)) {
long tn = arrays[j];
arrays[j] = arrays[j + 1];
arrays[j + 1] = tn;
}
}
}
}
StringBuffer sb = new StringBuffer();
for (int i = arrays.length - 1; i >= 0; i--)
sb.append(arrays[i]);
return sb.toString();
}执行Case数据
long a[] = new long[]{764, 76, 77};
long b[] = new long[]{767, 76, 77};
long c[] = new long[]{7864, 284, 347, 7732, 8498};执行结果

边栏推荐
猜你喜欢

Description of longitude and latitude PLT file format

14、 Two methods of database export and import

Specific method example of V20 frequency converter manual automatic switching (local remote switching)

LDO稳压芯片-内部框图及选型参数

2021ICPC上海 H.Life is a Game Kruskal重构树

十三、系统优化

Talk about the design and implementation logic of payment process

微信论坛交流小程序系统毕业设计毕设(7)中期检查报告

ArcGIS:矢量要素相同字段属性融合的两种方法

RE1 attack and defense world reverse
随机推荐
Clean C disk
网络安全-对操作系统进行信息查询
Network security - Eternal Blue
ArcGIS:矢量要素相同字段属性融合的两种方法
微信论坛交流小程序系统毕业设计毕设(8)毕业设计论文模板
FreeLink开源呼叫中心设计思想
微信论坛交流小程序系统毕业设计毕设(5)任务书
UE4_UE5结合罗技手柄(F710)使用记录
Brush question 5
网络安全-永恒之蓝
Wechat forum exchange applet system graduation design completion (7) Interim inspection report
Puce à tension stabilisée LDO - schéma de bloc interne et paramètres de sélection du modèle
网络安全-联合查询注入
Count the top 10 films at the box office and save them in another file
高级程序员必知必会,一文详解MySQL主从同步原理,推荐收藏
微信论坛交流小程序系统毕业设计毕设(4)开题报告
智慧社区和智慧城市之间有什么异同
Wechat forum exchange applet system graduation design (2) applet function
Dynamics 365 find field filtering
Coreseek:第二步建索引及測试