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.
思路:其实就是按照 如果ab>ba(注意这里是连接而不是乗) 那个a>b这个规则将nums中数据从大大小排序,然后从大到小取组成的数就是的了
代码如下(已通过leetcode)
public class Solution {
public String largestNumber(int[] nums) {
String res="";
boolean[] flag=new boolean[nums.length];
long max=0;
int maxpos=-1;
for(int i=0;i<nums.length;i++) {
for(int j=0;j<nums.length;j++) {
if(!flag[j]) {
if(Long.valueOf(""+max+nums[j])<Long.valueOf(""+nums[j]+max)) {
max=nums[j];
maxpos=j;
}
}
}
if(maxpos==-1) break;
flag[maxpos]=true;
res=res+nums[maxpos];
maxpos=-1;
max=0;
}
for(int i=0;i<nums.length;i++) {
if(!flag[i]) {
res=res+nums[i];
flag[i]=true;
}
}
boolean temp=false;
for(int i=0;i<res.length();i++) {
if(res.charAt(i)!='0') {
temp=true;
break;
}
}
if(!temp) return "0";
else return res;
}
}