代码实现:
package huawei import ( "fmt" "sort" "strconv" "strings" ) func Test3Base() { res := "1,4,3,2,90,7,6,17,8,9" sortNums(res) } func sortNums(resString string) { numsStr := strings.Split(resString, ",") numsInt := convertToIntSlice(numsStr) //排序 sort.Ints(numsInt) //连续数字只保留首尾 result := removeCenterItems(numsInt) fmt.Println(result) } //将[]string转为[]int func convertToIntSlice(numsStr []string) []int { numsInt := make([]int, len(numsStr)) for i, v := range numsStr { n, err := strconv.Atoi(v) checkError(err, "string to integer") numsInt[i] = n } return numsInt } //连续数字只保留首尾 func removeCenterItems(nums []int) []int { //需要移除的索引位置 removeList := make([]int, 0, len(nums)) for i := 1; i < len(nums)-1; i++ { if nums[i] == nums[i-1]+1 && nums[i] == nums[i+1]-1 { removeList = append(removeList, i) } } //移除 for i := len(nums) - 2; i > 0; i-- { if checkContains(removeList, i) { nums = append(nums[:i], nums[i+1:]...) } } return nums } //判断slice中是否存在某个元素 func checkContains(nums []int, value int) bool { for _, v := range nums { if v == value { return true } } return false }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/books1958/article/details/46772499