亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Go語言算法之尋找數(shù)組第二大元素的方法

 更新時(shí)間:2015年02月08日 15:06:35   作者:books1958  
這篇文章主要介紹了Go語言算法之尋找數(shù)組第二大元素的方法,以實(shí)例形式分析了不排序、只循環(huán)一次來實(shí)現(xiàn)尋找數(shù)組第二大元素的技巧,是比較典型的算法,需要的朋友可以參考下

本文實(shí)例講述了Go語言算法之尋找數(shù)組第二大元素的方法。分享給大家供大家參考。具體如下:

該算法的原理是,在遍歷數(shù)組的時(shí),始終記錄當(dāng)前最大的元素和第二大的元素。示例代碼如下:

復(fù)制代碼 代碼如下:
package demo01 
 
import ( 
    "fmt" 

 
func NumberTestBase() { 
    fmt.Println("This is NumberTestBase") 
 
    nums := []int{12, 24, 2, 5, 13, 8, 7} 
    fmt.Println("nums:", nums) 
    secondMax := getSecondMaxNum(nums) 
    fmt.Println("secondMax=", secondMax) 

 
func getSecondMaxNum(nums []int) int { 
    length := len(nums) 
    if length == 0 { 
        panic("Slice nums cannot be 0-size.") 
    } 
 
    if length == 1 { 
        return nums[0] 
    } 
 
    var max, secondMax int 
    if nums[0] > nums[1] { 
        max = nums[0] 
        secondMax = nums[1] 
    } else { 
        max = nums[1] 
        secondMax = nums[0] 
    } 
 
    for i := 2; i < len(nums); i++ { 
        if nums[i] > secondMax { 
            if nums[i] <= max { 
                secondMax = nums[i] 
            } else { 
                secondMax, max = max, nums[i] 
            } 
        } 
    } 
    return secondMax 
}

希望本文所述對(duì)大家的Go語言程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論