2025-03-25-01

This commit is contained in:
2025-03-25 17:57:51 +08:00
parent 6536fc0460
commit ffb1da1215
6 changed files with 360 additions and 9 deletions

View File

@@ -3,6 +3,55 @@
2^x = 1 << x
x/2 x >> 1
~~~
## 递增的三元子序列
给你一个整数数组 `nums` ,判断这个数组中是否存在长度为 `3` 的递增子序列。
如果存在这样的三元组下标 `(i, j, k)` 且满足 `i < j < k` ,使得 `nums[i] < nums[j] < nums[k]` ,返回 `true` ;否则,返回 `false` 。
~~~ go
func increasingTriplet(nums []int) bool {
n := len(nums)
if n < 3 {
return false
}
first, sencond := nums[0], math.MaxInt32
for i := 1;i < n;i++ {
num := nums[i]
if num > sencond {
return true
} else if num > first {
sencond = num
} else {
first = num
}
}
return false
}
~~~
赋初始值的时候已经满足second > first了现在找第三个数third
(1) 如果third比second大那就是找到了直接返回true
(2) 如果third比second小但是比first大那就把second指向third然后继续遍历找third
(3) 如果third比first还小那就把first指向third然后继续遍历找third这样的话first会跑到second的后边但是不要紧因为在second的前边老first还是满足的
## 字符串的最大公因子
~~~ go
func gcdOfStrings(str1 string, str2 string) string {
if str1+str2 != str2+str1 {
return ""
}
return str1[:gcd(len(str1), len(str2))]
}
// 欧几里得法求最大公因数
func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}
~~~
## 快乐数
~~~ go
func isHappy(n int) bool {
@@ -424,7 +473,7 @@ func addStrings(num1 string, num2 string) string {
for i, j := len(num1)-1, len(num2)-1; j >= 0 || i >= 0; {
num := add
if i >= 0 {
num += int(num1[i] - '0')
num += int(num1[i] - '0') //转Int
i--
}
if j >= 0 {