2025-03-25-01
This commit is contained in:
@@ -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 {
|
||||
|
Reference in New Issue
Block a user