描述:
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9]
, the largest formed number is 9534330
.
Note: The result may be very large, so you need to return a string instead of an integer.
思路:
1.将数字转换为字符串
2.对字符串数组进行升序排序
3.具体的排序规则为将两个字符串以str1+str2和str2+str1的方式拼接起来,然后比较两个拼接后的字符串即可
4.将排好序的字符串数组拼接起来即为要求的最大整数字符串
ps:刚开始走了好多弯路以比较短的字符串为基准和比较长的字符串循环比较,直至有不同大小的段为止,吃力不讨好,最后也没有算对^-^!
代码:
public class Solution implements Comparator<String>{ public int compare(String str1,String str2) { String newStr1=str1+str2; String newStr2=str2+str1; return newStr2.compareTo(newStr1); } public String largestNumber(int[] nums) { if(nums==null||nums.length==0) return new String(""); if(nums.length==1) return String.valueOf(nums[0]); int len=nums.length; String arr[]=new String[len]; for(int i=0;i<len;i++) arr[i]=String.valueOf(nums[i]); Arrays.sort(arr,new Solution()); StringBuilder sb=new StringBuilder(); for(int i=0;i<len;i++) sb.append(arr[i]); if(sb.charAt(0)=='0') return "0"; return sb.toString(); } }
时间: 2024-10-11 22:30:50