题意:
解题思路:
1. 插入排序,前后比较,交换位置;
PHP代码实现:
class Solution {
/**
* @param Integer[] $nums
* @return String
*/
function largestNumber($nums) {
for ($i = 1; $i < count($nums); $i++) {
for ($j = $i; $j > 0; $j--) {
if ($nums[$j]. $nums[$j - 1] > $nums[$j - 1]. $nums[$j]) {
$this->swap($nums, $j, $j - 1);
}
}
}
if ($nums[0] == "0") return "0";
return implode("", $nums);
}
function swap(&$arr, $i, $j) {
$t = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $t;
}
}
go代码实现:
func largestNumber(nums []int) string {
str := make([]string, len(nums))
for i, num := range nums {
str[i] = strconv.Itoa(num)
}
sort.Slice(str, func (i, j int) bool {
return str[i] + str[j] >= str[j] + str[i]
})
newStr := strings.Join(str, "")
if newStr[0] == '0' {
return "0"
}
return newStr
}