这是第12篇算法,力扣链接
闯关游戏需要破解一组密码,闯关组给出的有关密码的线索是:
- 一个拥有密码所有元素的非负整数数组
password
- 密码是
password
中所有元素拼接后得到的最小的一个数请编写一个程序返回这个密码。
示例 1:
输入: password = [15, 8, 7] 输出: "1578"示例 2:
输入: password = [0, 3, 30, 34, 5, 9] 输出: "03033459"
这道题可以转换一下,如果是常规的一位数的话,就是普通的排序题,把最小的数移到最高位就好,其实两位数同理,更改一下比较方式就行。这里的解题方法尝试多种排序方法。
方法一:冒泡排序
func crackPassword1(password []int) string {
strs := make([]string, len(password))
for i, num := range password {
strs[i] = strconv.Itoa(num)
}
for i := 0; i < len(password); i++ {
for j := i + 1; j < len(password); j++ {
left, _ := strconv.Atoi(strs[i] + strs[j])
right, _ := strconv.Atoi(strs[j] + strs[i])
if left > right {
temp := strs[i]
strs[i] = strs[j]
strs[j] = temp
}
}
}
return strings.Join(strs, "")
}
方法二:选择排序
func crackPassword2(password []int) string {
strs := make([]string, len(password))
for i, num := range password {
strs[i] = strconv.Itoa(num)
}
for i := 0; i < len(password); i++ {
index, num := i, strs[i]
for j := i + 1; j < len(password); j++ {
left, _ := strconv.Atoi(num + strs[j])
right, _ := strconv.Atoi(strs[j] + num)
if left > right {
index = j
num = strs[j]
}
}
if index != i {
temp := strs[index]
strs[index] = strs[i]
strs[i] = temp
}
}
return strings.Join(strs, "")
}
方法三:插入排序
func crackPassword3(password []int) string {
strs := make([]string, len(password))
for i, num := range password {
strs[i] = strconv.Itoa(num)
}
for i, current := range strs {
preIndex := i - 1
for preIndex >= 0 {
left, _ := strconv.Atoi(strs[preIndex] + current)
right, _ := strconv.Atoi(current + strs[preIndex])
if left > right {
strs[preIndex+1] = strs[preIndex]
preIndex--
} else {
break
}
}
strs[preIndex+1] = current
}
return strings.Join(strs, "")
}
方法四:快速排序
func crackPassword4(password []int) string {
strs := make([]string, len(password))
for i, num := range password {
strs[i] = strconv.Itoa(num)
}
for leftIndex := 0; leftIndex < len(password); leftIndex++ {
for rightIndex := leftIndex + 1; rightIndex < len(password); rightIndex++ {
left, _ := strconv.Atoi(strs[leftIndex] + strs[rightIndex])
right, _ := strconv.Atoi(strs[rightIndex] + strs[leftIndex])
if left > right {
temp := strs[leftIndex]
strs[leftIndex] = strs[rightIndex]
strs[rightIndex] = temp
}
}
}
return strings.Join(strs, "")
}
当然,还有很多种排序方法,我能力有限,欢迎大家尝试。