题意:

image.png

解题思路:

  1. 1. 插入排序,前后比较,交换位置;

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param Integer[] $nums
  4. * @return String
  5. */
  6. function largestNumber($nums) {
  7. for ($i = 1; $i < count($nums); $i++) {
  8. for ($j = $i; $j > 0; $j--) {
  9. if ($nums[$j]. $nums[$j - 1] > $nums[$j - 1]. $nums[$j]) {
  10. $this->swap($nums, $j, $j - 1);
  11. }
  12. }
  13. }
  14. if ($nums[0] == "0") return "0";
  15. return implode("", $nums);
  16. }
  17. function swap(&$arr, $i, $j) {
  18. $t = $arr[$i];
  19. $arr[$i] = $arr[$j];
  20. $arr[$j] = $t;
  21. }
  22. }

go代码实现:

  1. func largestNumber(nums []int) string {
  2. str := make([]string, len(nums))
  3. for i, num := range nums {
  4. str[i] = strconv.Itoa(num)
  5. }
  6. sort.Slice(str, func (i, j int) bool {
  7. return str[i] + str[j] >= str[j] + str[i]
  8. })
  9. newStr := strings.Join(str, "")
  10. if newStr[0] == '0' {
  11. return "0"
  12. }
  13. return newStr
  14. }