华为手撕代码:数组转最大整数
作者:互联网
题目描述:
给定一个正整数数组,返回该数组能够拼接成的最大整数,不可拆分数组中的数字
例如:
数组[3,30,34,5,9]能够组成的最大整数为9534330
数组[10,101011,34,5,9]能够组成的最大整数为953410101110
解析:
☆要点一:要实现一个字符串比较器
☆要点二:要实现递归比较,以应对3vs30、10vs101011这种情况
代码实现:
1 package com.test.od; 2 3 import java.util.Arrays; 4 import java.util.Comparator; 5 6 public class OD3 { 7 // 10110 10 8 public static String generateMaxNum(int[] nums){ 9 String[] numsStr = new String[nums.length]; 10 for (int i = 0; i < nums.length; i++){ 11 numsStr[i] = String.valueOf(nums[i]); 12 } 13 Arrays.sort(numsStr, new Comparator<String>() { 14 @Override 15 public int compare(String o1, String o2) { 16 int minLen = Math.min(o1.length(), o2.length()); 17 int maxLen = Math.max(o1.length(), o2.length()); 18 // 递归次数 19 int times = maxLen / minLen + 1; 20 // 把较短的字符串自我复制times次以递归比较 21 if (o1.length() < o2.length()){ 22 StringBuilder builder = new StringBuilder(); 23 for (int i = 0; i < times; i++){ 24 builder.append(o1); 25 } 26 o1 = builder.toString().substring(0, maxLen); 27 }else { 28 StringBuilder builder = new StringBuilder(); 29 for (int i = 0; i < times; i++){ 30 builder.append(o2); 31 } 32 o2 = builder.toString().substring(0, maxLen); 33 } 34 // 处理后的两字符串长度相等,开始倒序比较 35 for (int i = 0; i < maxLen; i++){ 36 if (o1.charAt(i) > o2.charAt(i)){ 37 return -1; 38 }else if (o1.charAt(i) < o2.charAt(i)){ 39 return 1; 40 } 41 } 42 return 0; 43 } 44 }); 45 StringBuilder resBuilder = new StringBuilder(); 46 for (String numStr : numsStr){ 47 resBuilder.append(numStr); 48 } 49 return resBuilder.toString(); 50 } 51 52 public static void main(String[] args) { 53 // int[] nums = {3,30,34,5,9}; 54 int[] nums = {10,101011,34,5,9}; 55 System.out.println(generateMaxNum(nums)); 56 } 57 }
标签:String,nums,int,length,整数,华为,数组,o2,o1 来源: https://www.cnblogs.com/WinterRain/p/16120812.html