Golang Leetcode 179. Largest Number.go

版权声明:原创勿转 https://blog.csdn.net/anakinsun/article/details/89011693

思路

实现内置的排序接口来进行排序

code

type intSlice []int

func newIntSlice(a []int) intSlice {
	b := intSlice{}
	for _, v := range a {
		b = append(b, v)
	}
	return b
}
func (s intSlice) Len() int {
	return len(s)
}

func (s intSlice) Less(i, j int) bool {
	stri := strconv.Itoa(s[i])
	strj := strconv.Itoa(s[j])
	s1, _ := strconv.Atoi(stri + strj)
	s2, _ := strconv.Atoi(strj + stri)
	return s1 > s2
}

func (s intSlice) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func largestNumber(nums []int) string {
	s := newIntSlice(nums)
	sort.Sort(s)
	res := ""
	for _, v := range s {
		res += strconv.Itoa(v)
		if res == "0" {
			res = ""
		}
	}
	if res == "" {
		return "0"
	}
	return res
}

更多内容请移步我的repo: https://github.com/anakin/golang-leetcode

猜你喜欢

转载自blog.csdn.net/anakinsun/article/details/89011693
今日推荐