Цена за 48 часов в ленте | 750,00 |
Цена за 1 час закрепления | N/A |
Взаимопиар | Нет |
Дополнительные условия рекламы | Отсутствуют |
Input: ring = "godding", key = "godding"
Output: 13
import (
"math"
"strconv"
)
func findRotateSteps(ring string, key string) int {
ringLen := len(ring)
keyLen := len(key)
bestSteps := make(map[string]int)
countSteps := func(curr, next int) int {
stepsBetween := int(math.Abs(float64(curr - next)))
stepsAround := ringLen - stepsBetween
return int(math.Min(float64(stepsBetween), float64(stepsAround)))
}
var tryLock func(int, int) int
tryLock = func(ringIndex, keyIndex int) int {
keyPair := strconv.Itoa(ringIndex) + "-" + strconv.Itoa(keyIndex)
if val, ok := bestSteps[keyPair]; ok {
return val
}
if keyIndex == keyLen {
bestSteps[keyPair] = 0
return 0
}
minSteps := math.MaxInt32
for charIndex := 0; charIndex < ringLen; charIndex++ {
if ring[charIndex] == key[keyIndex] {
minSteps = int(math.Min(float64(minSteps),
float64(countSteps(ringIndex, charIndex) + 1 + tryLock(charIndex, keyIndex + 1))))
}
}
bestSteps[keyPair] = minSteps
return minSteps
}
return tryLock(0,
Input: root = [2,1,3]
Output: 1
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
type Solution struct {
maxDepth int
bottomLeftValue int
}
func (s *Solution) findBottomLeftValue(root *TreeNode) int {
s.maxDepth = -1
s.bottomLeftValue = 0
s.dfs(root, 0)
return s.bottomLeftValue
}
func (s *Solution) dfs(current *TreeNode, depth int) {
if current == nil {
return
}
if depth > s.maxDepth {
s.maxDepth = depth
s.bottomLeftValue = current.Val
}
s.dfs(current.Left, depth+1)
s.dfs(current.Right, depth+1)
}
Input: n = 5
Output: 5
Explanation:
Here are the non-negative integers <= 5 with their corresponding binary representations:
0 : 0
1 : 1
2 : 10
3 : 11
4 : 100
5 : 101
Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.
func findIntegers(num int) int {
count := 0
for i := 0; i <= num; i++ {
if check(i) {
count++
}
}
return count
}
func check(n int) bool {
i := 31
for i > 0 {
if (n&(1< return false
}
i--
}
return true
}
Input: nums = [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].
func findLHS(nums []int) int {
count := make(map[int]int)
res := 0
for _, num := range nums {
count[num]++
if count[num+1] > 0 {
res = max(res, count[num]+count[num+1])
}
if count[num-1] > 0 {
res = max(res, count[num]+count[num-1])
}
}
return res
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]
Output: ["Shogun"]
Explanation: The only common string is "Shogun".
func findRestaurant(list1 []string, list2 []string) []string {
map := make(map[int][]string)
for i := 0; i < len(list1); i++ {
for j := 0; j < len(list2); j++ {
if list1[i] == list2[j] {
if _, ok := map[i+j]; !ok {
map[i+j] = []string{}
}
map[i+j] = append(map[i+j], list1[i])
}
}
}
minIndexSum := int(^uint(0) >> 1)
for key := range map {
if key < minIndexSum {
minIndexSum = key
}
}
return map[minIndexSum]
}
Input: m = 3, n = 3, ops = [[2,2],[3,3]]
Output: 4
Explanation: The maximum integer in M is 2, and there are four of it in M. So return 4.
func maxCount(m int, n int, ops [][]int) int {
minA := m
minB := n
for _, op := range ops {
if op[0] < minA {
minA = op[0]
}
if op[1] < minB {
minB = op[1]
}
}
return minA * minB
}
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: true
package main
import (
"math"
)
func dist(p1, p2 []int) int {
return (p2[1]-p1[1])*(p2[1]-p1[1]) + (p2[0]-p1[0])*(p2[0]-p1[0])
}
func check(p1, p2, p3, p4 []int) bool {
return dist(p1, p2) > 0 &&
dist(p1, p2) == dist(p2, p3) &&
dist(p2, p3) == dist(p3, p4) &&
dist(p3, p4) == dist(p4, p1) &&
dist(p1, p3) == dist(p2, p4)
}
func validSquare(p1, p2, p3, p4 []int) bool {
return check(p1, p2, p3, p4) ||
check(p1, p3, p2, p4) ||
check(p1, p2, p4, p3)
}
Input: expression = "-1/2+1/2+1/3"
Output: "1/3"
package main
import (
"fmt"
"strconv"
"strings"
)
func fractionAddition(expression string) string {
sign := []byte{}
if expression[0] != '-' {
sign = append(sign, '+')
}
for i := 0; i < len(expression); i++ {
if expression[i] == '+' || expression[i] == '-' {
sign = append(sign, expression[i])
}
}
fractions := strings.FieldsFunc(expression, func(r rune) bool { return r == '+' || r == '-' })
prevNum, prevDen := 0, 1
i := 0
for _, sub := range fractions {
if sub == "" {
continue
}
parts := strings.Split(sub, "/")
num, _ := strconv.Atoi(parts[0])
den, _ := strconv.Atoi(parts[1])
g := gcd(prevDen, den)
if sign[i] == '+' {
prevNum = prevNum*den/g + num*prevDen/g
} else {
prevNum = prevNum*den/g - num*prevDen/g
}
prevDen = prevDen * den / g
g = abs(gcd(prevDen, prevNum))
prevNum /= g
prevDen /= g
i++
}
return fmt.Sprintf("%d/%d", prevNum, prevDen)
}
func gcd(a, b int) int {
for b != 0 {
a, b = b, a%b
}
return a
}
func abs(a int) int {
if a < 0 {
return -a
}
return a
}
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]
package main
type Node struct {
Val int
Children []*Node
}
func postorder(root *Node) []int {
if root == nil {
return []int{}
}
stack := []*Node{root}
output := []int{}
for len(stack) > 0 {
node := stack[len(stack)-1]
stack = stack[:len(stack)-1]
output = append([]int{node.Val}, output...)
for _, child := range node.Children {
if child != nil {
stack = append(stack, child)
}
}
}
return output
}
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
package main
import (
"fmt"
)
func reverseWords(s string) string {
chars := []rune(s)
lastSpaceIndex := -1
len := len(chars)
for strIndex := 0; strIndex <= len; strIndex++ {
if strIndex == len || chars[strIndex] == ' ' {
startIndex := lastSpaceIndex + 1
endIndex := strIndex - 1
for startIndex < endIndex {
chars[startIndex], chars[endIndex] = chars[endIndex], chars[startIndex]
startIndex++
endIndex--
}
lastSpaceIndex = strIndex
}
}
return string(chars)
}
func main() {
s := "Let's take LeetCode contest"
fmt.Println(reverseWords(s)) // Output: "s'teL ekat edoCteeL tsetnoc"
}
Input: n = 12
Output: 21
package main
import (
"fmt"
"sort"
"strconv"
)
func swap(s string, i0, i1 int) string {
if i0 == i1 {
return s
}
runes := []rune(s)
runes[i0], runes[i1] = runes[i1], runes[i0]
return string(runes)
}
var list []string
func permute(a string, l, r int) {
if l == r {
list = append(list, a)
} else {
for i := l; i <= r; i++ {
a = swap(a, l, i)
permute(a, l+1, r)
a = swap(a, l, i)
}
}
}
func nextGreaterElement(n int) int {
s := strconv.Itoa(n)
list = []string{}
permute(s, 0, len(s)-1)
sort.Strings(list)
for i := range list {
if list[i] == s {
if i < len(list)-1 {
result, _ := strconv.Atoi(list[i+1])
if result <= 2147483647 {
return result
}
}
}
}
return -1
}
func main() {
n := 12345
fmt.Println(nextGreaterElement(n)) // Output: 12354
}
Input: wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]
Output: 2
package main
import (
"math"
)
func leastBricks(wall [][]int) int {
pos := make([]int, len(wall))
sum := 0
res := math.MaxInt32
for _, el := range wall[0] {
sum += el
}
for sum != 0 {
count := 0
for i := 0; i < len(wall); i++ {
if wall[i][pos[i]] != 0 {
count++
} else {
pos[i]++
}
wall[i][pos[i]]--
}
sum--
res = min(res, count)
}
return res
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
Input: password = "a"
Output: 5
package main
import (
"unicode"
)
func strongPasswordChecker(s string) int {
n := len(s)
hasLower, hasUpper, hasDigit := false, false, false
repeatCount := 0
for i := 0; i < n; {
if unicode.IsLower(rune(s[i])) {
hasLower = true
}
if unicode.IsUpper(rune(s[i])) {
hasUpper = true
}
if unicode.IsDigit(rune(s[i])) {
hasDigit = true
}
start := i
for i < n && s[i] == s[start] {
i++
}
repeatCount += (i - start) / 3
}
missingTypes := 0
if !hasLower {
missingTypes++
}
if !hasUpper {
missingTypes++
}
if !hasDigit {
missingTypes++
}
if n < 6 {
return max(missingTypes, 6-n)
} else if n <= 20 {
return max(missingTypes, repeatCount)
} else {
excessChars := n - 20
overLenReduction := 0
for i := 2; i < n && excessChars > 0; i++ {
if i%3 == 2 && s[i] == s[i-1] && s[i] == s[i-2] {
overLenReduction++
excessChars--
}
}
repeatCount -= overLenReduction
return (n - 20) + max(missingTypes, repeatCount)
}
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
Input: nums = [1000,100,10,2]
Output: "1000/(100/10/2)"
Explanation: 1000/(100/10/2) = 1000/((100/10)/2) = 200
However, the bold parenthesis in "1000/((100/10)/2)" are redundant since they do not influence the operation priority.
So you should return "1000/(100/10/2)".
Other cases:
1000/(100/10)/2 = 50
1000/(100/(10/2)) = 50
1000/100/10/2 = 0.5
1000/100/(10/2) = 2
package main
import (
"fmt"
"strconv"
)
func addStrings(num1 []int, num2 []int) []int {
var ans []int
carry := 0
n1, n2 := len(num1), len(num2)
for i := 0; i < max(n1, n2) || carry != 0; i++ {
digit1, digit2 := 0, 0
if i < n1 {
digit1 = num1[i]
}
if i < n2 {
digit2 = num2[i]
}
sum := digit1 + digit2 + carry
carry = sum / 10
ans = append(ans, sum%10)
}
return ans
}
func multiplyOneDigit(firstNumber string, secondNumberDigit rune, numZeros int) []int {
var currentResult []int
for i := 0; i < numZeros; i++ {
currentResult = append(currentResult, 0)
}
carry := 0
for _, digit := range firstNumber {
multiplication := (int(secondNumberDigit-'0') * int(digit-'0')) + carry
carry = multiplication / 10
currentResult = append(currentResult, multiplication%10)
}
if carry != 0 {
currentResult = append(currentResult, carry)
}
return currentResult
}
func multiply(firstNumber string, secondNumber string) string {
if firstNumber == "0" || secondNumber == "0" {
return "0"
}
firstNumberRev := reverseString(firstNumber)
secondNumberRev := reverseString(secondNumber)
ans := make([]int, len(firstNumber)+len(secondNumber))
for i, digit := range secondNumberRev {
ans = addStrings(multiplyOneDigit(firstNumberRev, digit, i), ans)
}
for len(ans) > 1 && ans[len(ans)-1] == 0 {
ans = ans[:len(ans)-1]
}
result := ""
for i := len(ans) - 1; i >= 0; i-- {
result += strconv.Itoa(ans[i])
}
return result
}
func reverseString(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func main() {
fmt.Println(multiply("123", "456"))
}
Input: board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]
Output: 2
package main
func countBattleships(board [][]byte) int {
m, n := len(board), len(board[0])
count := 0
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if board[i][j] == 'X' {
if (i == 0 || board[i-1][j] == '.') && (j == 0 || board[i][j-1] == '.') {
count++
}
}
}
}
return count
}
Input: sentence = ["hello","world"], rows = 2, cols = 8
Output: 1
package main
func wordsTyping(sentence []string, rows int, cols int) int {
sentenceStr := ""
for _, word := range sentence {
sentenceStr += word + " "
}
length := len(sentenceStr)
count := 0
for i := 0; i < rows; i++ {
count += cols
if sentenceStr[count % length] == ' ' {
count++
} else {
for count > 0 && sentenceStr[(count - 1) % length] != ' ' {
count--
}
}
}
return count / length
}
Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
package main
func pacificAtlantic(heights [][]int) [][]int {
m, n := len(heights), len(heights[0])
pacific := make([][]bool, m)
atlantic := make([][]bool, m)
for i := range pacific {
pacific[i] = make([]bool, n)
atlantic[i] = make([]bool, n)
}
directions := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}
var dfs func(r, c int, ocean [][]bool)
dfs = func(r, c int, ocean [][]bool) {
ocean[r][c] = true
for _, dir := range directions {
nr, nc := r+dir[0], c+dir[1]
if nr >= 0 && nc >= 0 && nr < m && nc < n && !ocean[nr][nc] && heights[nr][nc] >= heights[r][c] {
dfs(nr, nc, ocean)
}
}
}
for i := 0; i < m; i++ {
dfs(i, 0, pacific)
dfs(i, n-1, atlantic)
}
for j := 0; j < n; j++ {
dfs(0, j, pacific)
dfs(m-1, j, atlantic)
}
result := [][]int{}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if pacific[i][j] && atlantic[i][j] {
result = append(result, []int{i, j})
}
}
}
return result
}