1.https://www.lintcode.com/problem/digit-counts/description
Description
中文English
Count the number of k's between 0 and n. k can be 0 - 9.
Example
Input:
k = 1, n = 12
Output:
5
Explanation:
In [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], we found that one appeared five times (1, 10, 11, 12)(Note that there are two 1 in 11).
Code
/**
Input:
k = 1, n = 1
Output:
1
Explanation:
In [0, 1], we found that 1 appeared once (1).
*/
func CountNumber(k int ,n int) int {
count := 0
var kStr = strconv.Itoa(k)
for i :=0 ; i <= n ; i++ {
tempStr := strconv.Itoa(i)
if tempStr == kStr && len(tempStr) == 1{
count ++
}else {
for j :=0 ; j < len(tempStr); j++ {
if kStr == string(tempStr[j]){
count ++
}
}
}
}
return count
}
測試:
package main
import (
"fmt"
"src/lintcode"
)
func main() {
// 測試出現頻率
k := 1
n := 12
fmt.Println("輸入",k,n)
number := lintcode.CountNumber(k, n)
fmt.Println("輸出",number)
}
輸出:
2. https://www.lintcode.com/problem/ugly-number-ii/description
Description
Ugly number is a number that only have prime factors 2
, 3
and 5
.
Design an algorithm to find the nth ugly number. The first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12...
// 尋找醜陋數
/**
尋找醜陋數
*/
func FindUgly(endFlag int) int {
if endFlag < 1 {
return -1
}
target := 1
flag := 1
for {
temp := target
for ;target % 2 == 0; {
target = target / 2
}
for ;target % 3 == 0; {
target = target / 3
}
for ;target % 5 == 0; {
target = target / 5
}
if flag >= endFlag && target == 1{
return temp
}
if target == 1{
flag ++
}
target = temp + 1
}
}
func main() {
// 測試醜數
input := 9
output := lintcode.FindUgly(input)
fmt.Println(input, output)
}
輸出:
3. https://www.lintcode.com/problem/kth-largest-element/description
Description
中文English
在數組中找到第 k 大的元素。
你可以交換數組中的元素的位置
Example
樣例 1:
輸入:
n = 1, nums = [1,3,4,2]
輸出:
4
樣例 2:
輸入:
n = 3, nums = [9,3,2,4,8]
輸出:
4
Challenge
要求時間複雜度爲O(n),空間複雜度爲O(1)。
// 代碼
持續更新中