5

【golang】leetcode初级-Fizz Buzz&计数质数

 2 years ago
source link: https://segmentfault.com/a/1190000041362070
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

第一题 Fizz Buzz

image.png

先赋i
再找3的倍数赋Fizz
再找5的倍数赋Buzz
,其中如果遇到15的倍数就赋FizzBuzz

func fizzBuzz(n int) []string {
    s:=make([]string,n)
    for i:=0;i<n;i++{
        s[i]=strconv.Itoa(i+1)
    }
    if n<3 {return s}
    for i:=2;i<n;i+=3{
        s[i]="Fizz"
    }
    if n<5{return s}
    for i:=4;i<n;i+=5{
        if (i+1)%15!=0{
            s[i]="Buzz"
        }else{s[i]="FizzBuzz"}
    }
    return s
}

这种方法需要在每次赋值的时候写一个新的字符串加入数组
可以使用官解的字符串拼接使效率得到提升
关于字符串拼接可以看这个:https://www.cnblogs.com/apoce...

func fizzBuzz(n int) (ans []string) {
    for i := 1; i <= n; i++ {
        sb := &strings.Builder{}
        if i%3 == 0 {
            sb.WriteString("Fizz")
        }
        if i%5 == 0 {
            sb.WriteString("Buzz")
        }
        if sb.Len() == 0 {
            sb.WriteString(strconv.Itoa(i))
        }
        ans = append(ans, sb.String())
    }
    return
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/fizz-buzz/solution/fizz-buzz-by-leetcode-solution-s0s5/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

复杂度分析

时间复杂度:O(n)。需要遍历从 1 到 n 的每个整数,对于每个整数 i,生成 answer[i] 的时间复杂度是 O(1)。

空间复杂度:O(1)。注意返回值不计入空间复杂度。

第二题 计数质数

image.png

image.png
image.png

func countPrimes(n int) (cnt int) {
    isPrime := make([]bool, n)
    for i := range isPrime {
        isPrime[i] = true
    }
    for i := 2; i < n; i++ {
        if isPrime[i] {
            cnt++
            for j := 2 * i; j < n; j += i {
                isPrime[j] = false
            }
        }
    }
    return cnt
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK