Цена за 48 часов в ленте | 750,00 |
Цена за 1 час закрепления | N/A |
Взаимопиар | Нет |
Дополнительные условия рекламы | Отсутствуют |
Input
["WordDistance", "shortest", "shortest"]
[[["practice", "makes", "perfect", "coding", "makes"]], ["coding", "practice"], ["makes", "coding"]]
Output
[null, 3, 1]
Explanation
WordDistance wordDistance = new WordDistance(["practice", "makes", "perfect", "coding", "makes"]);
wordDistance.shortest("coding", "practice"); // return 3
wordDistance.shortest("makes", "coding"); // return 1
package main
import (
"math"
)
type WordDistance struct {
locations map[string][]int
}
func Constructor(words []string) WordDistance {
locations := make(map[string][]int)
for i, word := range words {
locations[word] = append(locations[word], i)
}
return WordDistance{locations: locations}
}
func (this *WordDistance) Shortest(word1 string, word2 string) int {
loc1 := this.locations[word1]
loc2 := this.locations[word2]
l1, l2 := 0, 0
minDiff := math.MaxInt32
for l1 < len(loc1) && l2 < len(loc2) {
minDiff = min(minDiff, abs(loc1[l1]-loc2[l2]))
if loc1[l1] < loc2[l2] {
l1++
} else {
l2++
}
}
return minDiff
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func abs(a int) int {
if a < 0 {
return -a
}
return a
}
wordsDict
и две разные строки, которые уже существуют в массиве: word1
и word2
. Верните кратчайшее расстояние между этими двумя словами в списке.Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
Output: 3
type Solution struct{}
func (s *Solution) ShortestDistance(words []string, word1 string, word2 string) int {
minDistance := len(words)
for i, w1 := range words {
if w1 == word1 {
for j, w2 := range words {
if w2 == word2 {
if diff := abs(i - j); diff < minDistance {
minDistance = diff
}
}
}
}
}
return minDistance
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
Input: s = "anagram", t = "nagaram"
Output: true
func isAnagram(s string, t string) bool {
if len(s) != len(t) {
return false
}
count := [26]int{}
for i := range s {
count[s[i]-'a']++
count[t[i]-'a']--
}
for _, c := range count {
if c != 0 {
return false
}
}
return true
}
Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
Output: true
type Solution struct{}
func (s *Solution) binarySearch(matrix [][]int, target, start int, vertical bool) bool {
lo := start
hi := len(matrix[0]) - 1
if !vertical {
hi = len(matrix) - 1
}
for hi >= lo {
mid := (lo + hi) / 2
var value int
if vertical {
value = matrix[start][mid]
} else {
value = matrix[mid][start]
}
if value < target {
lo = mid + 1
} else if value > target {
hi = mid - 1
} else {
return true
}
}
return false
}
func (s *Solution) searchMatrix(matrix [][]int, target int) bool {
if len(matrix) == 0 || len(matrix[0]) == 0 {
return false
}
shorterDim := len(matrix)
if len(matrix[0]) < shorterDim {
shorterDim = len(matrix[0])
}
for i := 0; i < shorter
Input: n = 6
Output: true
Explanation: 6 = 2 × 3
package main
func isUgly(n int) bool {
if n <= 0 {
return false
}
for _, factor := range []int{2, 3, 5} {
n = keepDividingWhenDivisible(n, factor)
}
return n == 1
}
func keepDividingWhenDivisible(dividend, divisor int) int {
for dividend%divisor == 0 {
dividend /= divisor
}
return dividend
}
Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
Output: true
package main
func validTree(n int, edges [][]int) bool {
if len(edges) != n-1 {
return false
}
adjList := make([][]int, n)
for _, edge := range edges {
adjList[edge[0]] = append(adjList[edge[0]], edge[1])
adjList[edge[1]] = append(adjList[edge[1]], edge[0])
}
parent := make(map[int]int)
parent[0] = -1
queue := []int{0}
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
for _, neighbor := range adjList[node] {
if neighbor == parent[node] {
continue
}
if _, found := parent[neighbor]; found {
return false
}
parent[neighbor] = node
queue = append(queue, neighbor)
}
}
return len(parent) == n
}
Input: nums = [1,2,1,3,2,5]
Output: [3,5]
Explanation: [5, 3] is also a valid answer.
func singleNumber(nums []int) []int {
xor := 0
for _, num := range nums {
xor ^= num
}
diff := xor & -xor
res := []int{0, 0}
for _, num := range nums {
if num&diff == 0 {
res[0] ^= num
} else {
res[1] ^= num
}
}
return res
}
Input: nums = [-2,0,1,3], target = 2
Output: 2
Explanation: Because there are two triplets which sums are less than 2:
[-2,0,1]
[-2,0,3]
import "sort"
func threeSumSmaller(nums []int, target int) int {
sort.Ints(nums)
sum := 0
for i := 0; i < len(nums)-2; i++ {
sum += twoSumSmaller(nums, i+1, target-nums[i])
}
return sum
}
func twoSumSmaller(nums []int, startIndex int, target int) int {
sum := 0
for i := startIndex; i < len(nums)-1; i++ {
j := binarySearch(nums, i, target-nums[i])
sum += j - i
}
return sum
}
func binarySearch(nums []int, startIndex int, target int) int {
left, right := startIndex, len(nums)-1
for left < right {
mid := (left + right + 1) / 2
if nums[mid] < target {
left = mid
} else {
right = mid - 1
}
}
return left
}
Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
func addDigits(num int) int {
digital_root := 0
for num > 0 {
digital_root += num % 10
num /= 10
if num == 0 && digital_root > 9 {
num = digital_root
digital_root = 0
}
}
return digital_root
}
Input: root = [1,2,3,null,5]
Output: ["1->2->5","1->3"]
func constructPaths(root *TreeNode, path string, paths *[]string) {
if root != nil {
path += fmt.Sprintf("%d", root.Val)
if root.Left == nil && root.Right == nil {
*paths = append(*paths, path)
} else {
path += "->"
constructPaths(root.Left, path, paths)
constructPaths(root.Right, path, paths)
}
}
}
func binaryTreePaths(root *TreeNode) []string {
var paths []string
constructPaths(root, "", &paths)
return paths
}
Input: costs = [[17,2,17],[16,16,5],[14,3,19]]
Output: 10
Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue.
Minimum cost: 2 + 5 + 3 = 10.
func minCost(costs [][]int) int {
n := len(costs)
dp := make([][3]int, n)
dp[0] = [3]int{costs[0][0], costs[0][1], costs[0][2]}
for i := 1; i < n; i++ {
dp[i][0] = costs[i][0] + min(dp[i-1][1], dp[i-1][2])
dp[i][1] = costs[i][1] + min(dp[i-1][0], dp[i-1][2])
dp[i][2] = costs[i][2] + min(dp[i-1][0], dp[i-1][1])
}
return min(dp[n-1][0], dp[n-1][1], dp[n-1][2])
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]
package main
type TrieNode struct {
children map[rune]*TrieNode
word string
}
type Solution struct {
board [][]byte
result []string
}
func findWords(board [][]byte, words []string) []string {
root := buildTrie(words)
sol := Solution{board: board}
for row := range board {
for col := range board[0] {
if _, ok := root.children[rune(board[row][col])]; ok {
sol.backtrack(row, col, root)
}
}
}
return sol.result
}
func buildTrie(words []string) *TrieNode {
root := &TrieNode{children: make(map[rune]*TrieNode)}
for _, word := range words {
node := root
for _, letter := range word {
if node.children[letter] == nil {
node.children[letter] = &TrieNode{children: make(map[rune]*TrieNode)}
}
node = node.children[letter]
}
node.word = word
}
return root
}
func (sol *Solution) backtrack(row, col int, parent *TrieNode) {
letter := rune(sol.board[row][col])
currNode := parent.children[letter]
if currNode.word != "" {
sol.result = append(sol.result, currNode.word)
currNode.word = ""
}
sol.board[row][col] = '#'
rowOffset := []int{-1, 0, 1, 0}
colOffset := []int{0, 1, 0, -1}
for i := 0; i < 4; i++ {
newRow := row + rowOffset[i]
newCol := col + colOffset[i]
if newRow >= 0 && newRow < len(sol.board) && newCol >= 0 && newCol < len(sol.board[0]) {
if _, ok := currNode.children[rune(sol.board[newRow][newCol])]; ok {
sol.backtrack(newRow, newCol, currNode)
}
}
}
sol.board[row][col] = byte(letter)
if len(currNode.children) == 0 {
delete(parent.children, letter)
}
}
func main() {
board := [][]byte{
{'o', 'a', 'a', 'n'},
{'e', 't', 'a', 'e'},
{'i', 'h', 'k', 'r'},
{'i', 'f', 'l', 'v'},
}
words := []string{"oath", "pea", "eat", "rain"}
result := findWords(board, words)
for _, word := range result {
println(word)
}
}
Input
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
Output
[null,null,null,null,false,true,true,true]
Explanation
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True
package main
type TrieNode struct {
children map[rune]*TrieNode
isWord bool
}
type WordDictionary struct {
root *TrieNode
}
func Constructor() WordDictionary {
return WordDictionary{root: &TrieNode{children: make(map[rune]*TrieNode)}}
}
func (this *WordDictionary) AddWord(word string) {
node := this.root
for _, ch := range word {
if _, ok := node.children[ch]; !ok {
node.children[ch] = &TrieNode{children: make(map[rune]*TrieNode)}
}
node = node.children[ch]
}
node.isWord = true
}
func (this *WordDictionary) searchInNode(word string, node *TrieNode) bool {
for i, ch := range word {
if nextNode, ok := node.children[ch]; ok {
node = nextNode
} else {
if ch == '.' {
for _, child := range node.children {
if this.searchInNode(word[i+1:], child) {
return true
}
}
}
return false
}
}
return node.isWord
}
func (this *WordDictionary) Search(word string) bool {
return this.searchInNode(word, this.root)
}
func main() {
wordDictionary := Constructor()
wordDictionary.AddWord("bad")
wordDictionary.AddWord("dad")
wordDictionary.AddWord("mad")
println(wordDictionary.Search("pad")) // Output: false
println(wordDictionary.Search("bad")) // Output: true
println(wordDictionary.Search(".ad")) // Output: true
println(wordDictionary.Search("b..")) // Output: true
}
Input: preorder = [5,2,1,3,6]
Output: true
package main
func verifyPreorder(preorder []int) bool {
minLimit := -1 << 31
stack := []int{}
for _, num := range preorder {
for len(stack) > 0 && stack[len(stack)-1] < num {
minLimit = stack[len(stack)-1]
stack = stack[:len(stack)-1]
}
if num <= minLimit {
return false
}
stack = append(stack, num)
}
return true
}
Input: n = 1
Output: []
package main
func backtracking(factors []int, ans *[][]int) {
if len(factors) > 1 {
combo := make([]int, len(factors))
copy(combo, factors)
*ans = append(*ans, combo)
}
lastFactor := factors[len(factors)-1]
factors = factors[:len(factors)-1]
start := 2
if len(factors) > 0 {
start = factors[len(factors)-1]
}
for i := start; i*i <= lastFactor; i++ {
if lastFactor%i == 0 {
factors = append(factors, i)
factors = append(factors, lastFactor/i)
backtracking(factors, ans)
factors = factors[:len(factors)-2]
}
}
factors = append(factors, lastFactor)
}
func getFactors(n int) [][]int {
var ans [][]int
backtracking([]int{n}, &ans)
return ans
}
Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2
package main
import (
"container/heap"
"sort"
)
type MinHeap []int
func (h MinHeap) Len() int { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MinHeap) Push(x interface{}) {
*h = append(*h, x.(int))
}
func (h *MinHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func minMeetingRooms(intervals [][]int) int {
sort.Slice(intervals, func(i, j int) bool {
return intervals[i][0] < intervals[j][0]
})
h := &MinHeap{intervals[0][1]}
heap.Init(h)
for i := 1; i < len(intervals); i++) {
if intervals[i][0] >= (*h)[0] {
heap.Pop(h)
}
heap.Push(h, intervals[i][1])
}
return h.Len()
}
Input: intervals = [[0,30],[5,10],[15,20]]
Output: false
package main
type Solution struct{}
func (s Solution) Overlap(interval1, interval2 []int) bool {
return (interval1[0] >= interval2[0] && interval1[0] < interval2[1]) ||
(interval2[0] >= interval1[0] && interval2[0] < interval1[1])
}
func (s Solution) CanAttendMeetings(intervals [][]int) bool {
for i := 0; i < len(intervals); i++ {
for j := i + 1; j < len(intervals); j++ {
if s.Overlap(intervals[i], intervals[j]) {
return false
}
}
}
return true
}
Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,2,1,3]
Объяснение: Всего есть 4 курса, которые нужно пройти. Чтобы взять курс 3, вы должны завершить оба курса 1 и 2. Оба курса 1 и 2 должны быть взяты после того, как вы завершите курс 0.
Таким образом, один из правильных порядков курсов — [0,1,2,3]. Другой правильный порядок — [0,2,1,3].
package main
func findOrder(numCourses int, prerequisites [][]int) []int {
const (
WHITE = 1
GRAY = 2
BLACK = 3
)
isPossible := true
color := make(map[int]int)
adjList := make(map[int][]int)
var topologicalOrder []int
for i := 0; i < numCourses; i++ {
color[i] = WHITE
}
for _, relation := range prerequisites {
dest := relation[0]
src := relation[1]
adjList[src] = append(adjList[src], dest)
}
var dfs func(int)
dfs = func(node int) {
if !isPossible {
return
}
color[node] = GRAY
for _, neighbor := range adjList[node] {
if color[neighbor] == WHITE {
dfs(neighbor)
} else if color[neighbor] == GRAY {
isPossible = false
}
}
color[node] = BLACK
topologicalOrder = append(topologicalOrder, node)
}
for i := 0; i < numCourses && isPossible; i++ {
if color[i] == WHITE {
dfs(i)
}
}
if isPossible {
order := make([]int, numCourses)
for i := 0; i < numCourses; i++ {
order[i] = topologicalOrder[numCourses-i-1]
}
return order
} else {
return []int{}
}
}
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
func minSubArrayLen(target int, nums []int) int {
left, sumOfCurrentWindow, res := 0, 0, int(^uint(0) >> 1)
for right := 0; right < len(nums); right++ {
sumOfCurrentWindow += nums[right]
for sumOfCurrentWindow >= target {
if res > right - left + 1 {
res = right - left + 1
}
sumOfCurrentWindow -= nums[left]
left++
}
}
if res == int(^uint(0) >> 1) {
return 0
}
return res
}