A solution to one of my coding interview questions. Complete solution - written in GoLang
+
+
Task:
+
You've been asked to program a bot for a popular bank that will automate the management of incoming requests. There are three types of requests the bank can receive:
+
+
transfer i j sum: request to transfer sum amount of money from the i-th account to the j-th one
+
deposit i sum: request to deposit sum amount of money in the i-th account
+
withdraw i sum: request to withdraw sum amount of money from the i-th account.
+
+
Your bot should also be able to process invalid requests. There are two types of invalid requests: invalid account number in the requests; deposit / withdrawal of a larger amount of money than is currently available.
+
For the given list of accounts and requests, return the state of accounts after all requests have been processed, or an array of a single element [- ] (please note the minus sign), where is the 1-based index of the first invalid request.
+
Example for accounts = [10, 100, 20, 50, 30] and requests = ["withdraw 2 10", "transfer 5 1 20", "deposit 5 20", "transfer 3 4 15"], the output should be bankRequests(accounts, requests) = [30, 90, 5, 65, 30].
Here are the states of accounts after each request:
+
+
"withdraw 2 10": [10, 90, 20, 50, 30]
+
"transfer 5 1 20": [30, 90, 20, 50, 10]
+
"deposit 5 20": [30, 90, 20, 50, 30]
+
"transfer 3 4 15": [30, 90, 5, 65, 30], which is the answer
+
+
For accounts = [20, 1000, 500, 40, 90] and requests = ["deposit 3 400", "transfer 1 2 30", "withdraw 4 50"], the output should be bankRequests(accounts, requests) = [-2].
+
After the first request, accounts becomes equal to [20, 1000, 900, 40, 90], but the second one turns it into [-10, 1030, 900, 40, 90], which is invalid. Thus, the second request is invalid, and the answer is [-2]. Note that the last request is also invalid, but it shouldn't be included in the answer.
START
+Find longest sequence of zeros in binary representation of an integer.
+
題目
+
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
+
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.
+
Write a function:
+
func Solution(N int) int
+
that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.
+
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.
+
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [1..2,147,483,647].
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved to the first place).
+
The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.
+
Write a function:
+
func Solution(A []int, K int) []int
+
that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.
+
For example, given
+
A = [3, 8, 9, 7, 6]
+K = 3
+
the function should return [9, 7, 6, 3, 8]. Three rotations were made:
N and K are integers within the range [0..100];
+each element of array A is an integer within the range [−1,000..1,000].
+In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.
+
Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
+
For example, in array A such that:
+
A[0] = 9 A[1] = 3 A[2] = 9
+ A[3] = 3 A[4] = 9 A[5] = 7
+ A[6] = 9
+the elements at indexes 0 and 2 have value 9,
+the elements at indexes 1 and 3 have value 3,
+the elements at indexes 4 and 6 have value 9,
+the element at index 5 has value 7 and is unpaired.
+Write a function:
+
func Solution(A []int) int
+
that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.
+
For example, given array A such that:
+
A[0] = 9 A[1] = 3 A[2] = 9
+ A[3] = 3 A[4] = 9 A[5] = 7
+ A[6] = 9
+the function should return 7, as explained in the example above.
+
Write an efficient algorithm for the following assumptions:
+
N is an odd integer within the range [1..1,000,000];
+each element of array A is an integer within the range [1..1,000,000,000];
+all but one of the values in A occur an even number of times.
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.
+
Count the minimal number of jumps that the small frog must perform to reach its target.
+
Write a function:
+
func Solution(X int, Y int, D int) int
+
that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
+
For example, given:
+
X = 10
+ Y = 85
+ D = 30
+the function should return 3, because the frog will be positioned as follows:
+
after the first jump, at position 10 + 30 = 40
+after the second jump, at position 10 + 30 + 30 = 70
+after the third jump, at position 10 + 30 + 30 + 30 = 100
+Write an efficient algorithm for the following assumptions:
+
X, Y and D are integers within the range [1..1,000,000,000];
+X ≤ Y.
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
An array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.
+
Your goal is to find that missing element.
+
Write a function:
+
func Solution(A []int) int
+
that, given an array A, returns the value of the missing element.
+
For example, given array A such that:
+
A[0] = 2
+ A[1] = 3
+ A[2] = 1
+ A[3] = 5
+the function should return 4, as it is the missing element.
+
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [0..100,000];
+the elements of A are all distinct;
+each element of array A is an integer within the range [1..(N + 1)].
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
package permmissingelem
+
+func Solution(A []int) int {
+ if len(A) < 1 {
+ return 1
+ }
+
+ n := len(A) + 1
+ predictSume := (n + 1) * n / 2
+
+ var sum int
+ for _, v := range A {
+ sum += v
+ }
+ return predictSume - sum
+}
+
Find the earliest time when a frog can jump to the other side of a river.
+
A small frog wants to get to the other side of a river. The frog is initially located on one bank of the river (position 0) and wants to get to the opposite bank (position X+1). Leaves fall from a tree onto the surface of the river.
+
You are given an array A consisting of N integers representing the falling leaves. A[K] represents the position where one leaf falls at time K, measured in seconds.
+
The goal is to find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X (that is, we want to find the earliest moment when all the positions from 1 to X are covered by leaves). You may assume that the speed of the current in the river is negligibly small, i.e. the leaves do not change their positions once they fall in the river.
+
For example, you are given integer X = 5 and array A such that:
+
A[0] = 1
+ A[1] = 3
+ A[2] = 1
+ A[3] = 4
+ A[4] = 2
+ A[5] = 3
+ A[6] = 5
+ A[7] = 4
+In second 6, a leaf falls into position 5. This is the earliest time when leaves appear in every position across the river.
+
Write a function:
+
func Solution(X int, A []int) int
+
that, given a non-empty array A consisting of N integers and integer X, returns the earliest time when the frog can jump to the other side of the river.
+
If the frog is never able to jump to the other side of the river, the function should return −1.
Write an efficient algorithm for the following assumptions:
+
N and X are integers within the range [1..100,000];
+each element of array A is an integer within the range [1..X].
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Calculate the values of counters after applying all alternating operations: increase counter by 1; set value of all counters to current maximum.
+
You are given N counters, initially set to 0, and you have two possible operations on them:
+
increase(X) − counter X is increased by 1,
+max counter − all counters are set to the maximum value of any counter.
+A non-empty array A of M integers is given. This array represents consecutive operations:
+
if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
+if A[K] = N + 1 then operation K is max counter.
+For example, given integer N = 5 and array A such that:
the function should return [3, 2, 2, 4, 2], as explained above.
+
Write an efficient algorithm for the following assumptions:
+
N and M are integers within the range [1..100,000];
+each element of array A is an integer within the range [1..N + 1].
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
+
題目大意
+
如果A[i] 小於 N 則將計數器中對應位置的數+1, 如果A[i] 大於 N 則將計數器中所有的數更新為計數器當前的最大數值
Find the smallest positive integer that does not occur in a given sequence.
+
This is a demo task.
+
Write a function:
+
func Solution(A []int) int
+
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
+
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
+
Given A = [1, 2, 3], the function should return 4.
+
Given A = [−1, −3], the function should return 1.
+
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [1..100,000];
+each element of array A is an integer within the range [−1,000,000..1,000,000].
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
A non-empty array A consisting of N integers is given.
+
A permutation(排列) is a sequence containing each element from 1 to N once, and only once.
+
For example, array A such that:
+
A[0] = 4
+A[1] = 1
+A[2] = 3
+A[3] = 2
+
is a permutation, but array A such that:
+
A[0] = 4
+A[1] = 1
+A[2] = 3
+
is not a permutation, because value 2 is missing.
+
The goal is to check whether array A is a permutation.
+
Write a function:
+
func Solution(A []int) int
+
that, given an array A, returns 1 if array A is a permutation and 0 if it is not.
+
For example, given array A such that:
+
A[0] = 4
+A[1] = 1
+A[2] = 3
+A[3] = 2
+
the function should return 1.
+
Given array A such that:
+
A[0] = 4
+A[1] = 1
+A[2] = 3
+
the function should return 0.
+
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [1..100,000];
+each element of array A is an integer within the range [1..1,000,000,000].
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Compute number of integers divisible by k in range [a..b].
+
Write a function:
+
func Solution(A int, B int, K int) int
+
that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.:
+
{ i : A ≤ i ≤ B, i mod K = 0 }
+
For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10.
+
Write an efficient algorithm for the following assumptions:
+
A and B are integers within the range [0..2,000,000,000];
+K is an integer within the range [1..2,000,000,000];
+A ≤ B.
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Find the minimal nucleotide(核苷酸) from a range of sequence DNA.
+
A DNA sequence can be represented as a string consisting of the letters A, C, G and T, which correspond to the types of successive nucleotides in the sequence. Each nucleotide has an impact factor, which is an integer. Nucleotides of types A, C, G and T have impact factors of 1, 2, 3 and 4, respectively. You are going to answer several queries of the form: What is the minimal impact factor of nucleotides contained in a particular part of the given DNA sequence?
+
The DNA sequence is given as a non-empty string S = S[0]S[1]...S[N-1] consisting of N characters. There are M queries, which are given in non-empty arrays P and Q, each consisting of M integers. The K-th query (0 ≤ K < M) requires you to find the minimal impact factor of nucleotides contained in the DNA sequence between positions P[K] and Q[K] (inclusive).
+
For example, consider string S = CAGCCTA and arrays P, Q such that:
The answers to these M = 3 queries are as follows:
+
The part of the DNA between positions 2 and 4 contains nucleotides G and C (twice), whose impact factors are 3 and 2 respectively, so the answer is 2.
+The part between positions 5 and 5 contains a single nucleotide T, whose impact factor is 4, so the answer is 4.
+The part between positions 0 and 6 (the whole string) contains all nucleotides, in particular nucleotide A whose impact factor is 1, so the answer is 1.
+Write a function:
+
func Solution(S string, P []int, Q []int) []int
+
that, given a non-empty string S consisting of N characters and two non-empty arrays P and Q consisting of M integers, returns an array consisting of M integers specifying the consecutive answers to all queries.
+
Result array should be returned as an array of integers.
+
For example, given the string S = CAGCCTA and arrays P, Q such that:
the function should return the values [2, 4, 1], as explained above.
+
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [1..100,000];
+M is an integer within the range [1..50,000];
+each element of arrays P, Q is an integer within the range [0..N − 1];
+P[K] ≤ Q[K], where 0 ≤ K < M;
+string S consists only of upper-case English letters A, C, G, T.
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Find the minimal average of any slice containing at least two elements.
+
A non-empty array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P < Q < N, is called a slice of array A (notice that the slice contains at least two elements). The average of a slice (P, Q) is the sum of A[P] + A[P + 1] + ... + A[Q] divided by the length of the slice. To be precise, the average equals (A[P] + A[P + 1] + ... + A[Q]) / (Q − P + 1).
slice (1, 2), whose average is (2 + 2) / 2 = 2;
+slice (3, 4), whose average is (5 + 1) / 2 = 3;
+slice (1, 4), whose average is (2 + 2 + 5 + 1) / 4 = 2.5.
+The goal is to find the starting position of a slice whose average is minimal.
+
Write a function:
+
func Solution(A []int) int
+
that, given a non-empty array A consisting of N integers, returns the starting position of the slice with the minimal average. If there is more than one slice with a minimal average, you should return the smallest starting position of such a slice.
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [2..100,000];
+each element of array A is an integer within the range [−10,000..10,000].
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
A non-empty array A consisting of N integers is given. The consecutive(連續) elements of array A represent consecutive cars on a road.
+
Array A contains only 0s and/or 1s:
+
0 represents a car traveling east,
+1 represents a car traveling west.
+The goal is to count passing cars. We say that a pair of cars (P, Q), where 0 ≤ P < Q < N, is passing when P is traveling to the east and Q is traveling to the west.
+
For example, consider array A such that:
+
A[0] = 0 // no.0 car trave to east
+ A[1] = 1 // no.1 car trave to west
+ A[2] = 0 // no.2 car trave to east
+ A[3] = 1 // no.3 car trave to west
+ A[4] = 1 // no.4 car trave to west
+We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).
+
Write a function:
+
func Solution(A []int) int
+
that, given a non-empty array A of N integers, returns the number of pairs of passing cars.
+
The function should return −1 if the number of pairs of passing cars exceeds 1,000,000,000.
+
For example, given:
+
A[0] = 0
+ A[1] = 1
+ A[2] = 0
+ A[3] = 1
+ A[4] = 1
+the function should return 5, as explained above.
+
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [1..100,000];
+each element of array A is an integer that can have one of the following values: 0, 1.
+
Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
that, given an array A consisting of N integers, returns the number of distinct values in array A.
+
For example, given array A consisting of six elements such that:
+
A[0] = 2 A[1] = 1 A[2] = 1
+ A[3] = 2 A[4] = 3 A[5] = 1
+the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3.
+
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [0..100,000];
+each element of array A is an integer within the range [−1,000,000..1,000,000].
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Maximize A[P] A[Q] A[R] for any triplet (P, Q, R).
+
A non-empty array A consisting of N integers is given. The product of triplet (P, Q, R) equates to A[P] A[Q] A[R] (0 ≤ P < Q < R < N).
+
For example, array A such that:
+
A[0] = -3
+ A[1] = 1
+ A[2] = 2
+ A[3] = -2
+ A[4] = 5
+ A[5] = 6
+contains the following example triplets:
+
(0, 1, 2), product is −3 1 2 = −6
+(1, 2, 4), product is 1 2 5 = 10
+(2, 4, 5), product is 2 5 6 = 60
+Your goal is to find the maximal product of any triplet.
+
Write a function:
+
func Solution(A []int) int
+
that, given a non-empty array A, returns the value of the maximal product of any triplet.
+
For example, given array A such that:
+
A[0] = -3
+ A[1] = 1
+ A[2] = 2
+ A[3] = -2
+ A[4] = 5
+ A[5] = 6
+the function should return 60, as the product of triplet (2, 4, 5) is maximal.
+
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [3..100,000];
+each element of array A is an integer within the range [−1,000..1,000].
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Compute the number of intersections(相交) in a sequence of discs(圓盤).
+
We draw N discs on a plane. The discs are numbered from 0 to N − 1. An array A of N non-negative integers, specifying the radiuses(半徑) of the discs, is given. The J-th disc is drawn with its center at (J, 0) and radius A[J].
+
We say that the J-th disc and K-th disc intersect if J ≠ K and the J-th and K-th discs have at least one common point (assuming that the discs contain their borders).
+
The figure below shows discs drawn for N = 6 and A as follows:
There are eleven (unordered) pairs of discs that intersect, namely:
+
+
discs 1 and 4 intersect, and both intersect with all the other discs;
+
disc 2 also intersects with discs 0 and 3.
+Write a function:
+
+
func Solution(A []int) int
+
that, given an array A describing N discs as explained above, returns the number of (unordered) pairs of intersecting discs. The function should return −1 if the number of intersecting pairs exceeds 10,000,000.
+
Given array A shown above, the function should return 11, as explained above.
+
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [0..100,000];
+each element of array A is an integer within the range [0..2,147,483,647].
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Determine whether a given string of parentheses (multiple types) is properly nested.
+
A string S consisting of N characters is considered to be properly nested if any of the following conditions is true:
+
S is empty;
+S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string;
+S has the form "VW" where V and W are properly nested strings.
+For example, the string "{[()()]}" is properly nested but "([)()]" is not.
+
Write a function:
+
func Solution(S string) int
+
that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.
+
For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above.
+
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [0..200,000];
+string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")".
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
N voracious fish are moving along a river. Calculate how many fish are alive.
+
You are given two non-empty arrays A and B consisting of N integers. Arrays A and B represent N voracious fish in a river, ordered downstream along the flow of the river.
+
The fish are numbered from 0 to N − 1. If P and Q are two fish and P < Q, then fish P is initially upstream of fish Q. Initially, each fish has a unique position.
+
Fish number P is represented by A[P] and B[P]. Array A contains the sizes of the fish. All its elements are unique. Array B contains the directions of the fish. It contains only 0s and/or 1s, where:
+
0 represents a fish flowing upstream,
+1 represents a fish flowing downstream.
+If two fish move in opposite directions and there are no other (living) fish between them, they will eventually meet each other. Then only one fish can stay alive − the larger fish eats the smaller one. More precisely, we say that two fish P and Q meet each other when P < Q, B[P] = 1 and B[Q] = 0, and there are no living fish between them. After they meet:
+
If A[P] > A[Q] then P eats Q, and P will still be flowing downstream,
+If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream.
+We assume that all the fish are flowing at the same speed. That is, fish moving in the same direction never meet. The goal is to calculate the number of fish that will stay alive.
+
For example, consider arrays A and B such that:
+
A[0] = 4 B[0] = 0
+ A[1] = 3 B[1] = 1
+ A[2] = 2 B[2] = 0
+ A[3] = 1 B[3] = 0
+ A[4] = 5 B[4] = 0
+Initially all the fish are alive and all except fish number 1 are moving upstream. Fish number 1 meets fish number 2 and eats it, then it meets fish number 3 and eats it too. Finally, it meets fish number 4 and is eaten by it. The remaining two fish, number 0 and 4, never meet and therefore stay alive.
+
Write a function:
+
func Solution(A []int, B []int) int
+
that, given two non-empty arrays A and B consisting of N integers, returns the number of fish that will stay alive.
+
For example, given the arrays shown above, the function should return 2, as explained above.
+
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [1..100,000];
+each element of array A is an integer within the range [0..1,000,000,000];
+each element of array B is an integer that can have one of the following values: 0, 1;
+the elements of A are all distinct.
+
Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Determine whether a given string of parentheses (single type) is properly nested.
+
A string S consisting of N characters is called properly nested if:
+
S is empty;
+S has the form "(U)" where U is a properly nested string;
+S has the form "VW" where V and W are properly nested strings.
+For example, string "(()(())())" is properly nested but string "())" isn't.
+
Write a function:
+
func Solution(S string) int
+
that, given a string S consisting of N characters, returns 1 if string S is properly nested and 0 otherwise.
+
For example, given S = "(()(())())", the function should return 1 and given S = "())", the function should return 0, as explained above.
+
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [0..1,000,000];
+string S consists only of the characters "(" and/or ")".
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Cover "Manhattan skyline" using the minimum number of rectangles.
+
You are going to build a stone wall. The wall should be straight and N meters long, and its thickness should be constant; however, it should have different heights in different places. The height of the wall is specified by an array H of N positive integers. H[I] is the height of the wall from I to I+1 meters to the right of its left end. In particular, H[0] is the height of the wall's left end and H[N−1] is the height of the wall's right end.
+
The wall should be built of cuboid (長方體) stone blocks (that is, all sides of such blocks are rectangular). Your task is to compute the minimum number of blocks needed to build the wall.
+
Write a function:
+
func Solution(H []int) int
+
that, given an array H of N positive integers specifying the height of the wall, returns the minimum number of blocks needed to build it.
+
For example, given array H containing N = 9 integers:
+
H[0] = 8 H[1] = 8 H[2] = 5
+ H[3] = 7 H[4] = 9 H[5] = 8
+ H[6] = 7 H[7] = 4 H[8] = 8
+the function should return 7. The figure shows one possible arrangement of seven blocks.
+
+
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [1..100,000];
+each element of array H is an integer within the range [1..1,000,000,000].
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
+
題目大意
+
如何用最少的數量來貼出符合 H 的牆呢
+要建立一面長N米的強. 厚度固定, 每個地方的高度不同.
+H[I]代表牆從 I 到 I+1 米處的高度.
+H[0]大表牆最左到1米處的高度
+H[N-1]大表牆N-1米處到最右的高度
Find an index of an array such that its value occurs at more than half of indices in the array.
+
An array A consisting of N integers is given. The dominator of array A is the value that occurs in more than half of the elements of A.
+
For example, consider array A such that
+
A[0] = 3 A[1] = 4 A[2] = 3
+ A[3] = 2 A[4] = 3 A[5] = -1
+ A[6] = 3 A[7] = 3
+The dominator of A is 3 because it occurs in 5 out of 8 elements of A (namely in those with indices 0, 2, 4, 6 and 7) and 5 is more than a half of 8.
+
Write a function
+
func Solution(A []int) int
+
that, given an array A consisting of N integers, returns index of any element of array A in which the dominator of A occurs. The function should return −1 if array A does not have a dominator.
+
For example, given array A such that
+
A[0] = 3 A[1] = 4 A[2] = 3
+ A[3] = 2 A[4] = 3 A[5] = -1
+ A[6] = 3 A[7] = 3
+the function may return 0, 2, 4, 6 or 7, as explained above.
+
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [0..100,000];
+each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Find the index S such that the leaders of the sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N - 1] are the same.
+
A non-empty array A consisting of N integers is given.
+
The leader of this array is the value that occurs in more than half of the elements of A.
+
An equi leader is an index S such that 0 ≤ S < N − 1 and two sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N − 1] have leaders of the same value.
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [1..100,000];
+each element of array A is an integer within the range [−1,000,000,000..1,000,000,000].
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
double slice (0, 3, 6), sum is 2 + 6 + 4 + 5 = 17,
+double slice (0, 3, 7), sum is 2 + 6 + 4 + 5 − 1 = 16,
+double slice (3, 4, 5), sum is 0.
+The goal is to find the maximal sum of any double slice.
+
Write a function:
+
func Solution(A []int) int
+
that, given a non-empty array A consisting of N integers, returns the maximal sum of any double slice.
the function should return 17, because no double slice of array A has a sum of greater than 17.
+
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [3..100,000];
+each element of array A is an integer within the range [−10,000..10,000].
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Given a log of stock prices compute the maximum possible earning.
+
An array A consisting of N integers is given. It contains daily prices of a stock share for a period of N consecutive days. If a single share was bought on day P and sold on day Q, where 0 ≤ P ≤ Q < N, then the profit of such transaction is equal to A[Q] − A[P], provided that A[Q] ≥ A[P]. Otherwise, the transaction brings loss of A[P] − A[Q].
+
For example, consider the following array A consisting of six elements such that:
+
A[0] = 23171
+ A[1] = 21011
+ A[2] = 21123
+ A[3] = 21366
+ A[4] = 21013
+ A[5] = 21367
+If a share was bought on day 0 and sold on day 2, a loss of 2048 would occur because A[2] − A[0] = 21123 − 23171 = −2048. If a share was bought on day 4 and sold on day 5, a profit of 354 would occur because A[5] − A[4] = 21367 − 21013 = 354. Maximum possible profit was 356. It would occur if a share was bought on day 1 and sold on day 5.
+
Write a function,
+
func Solution(A []int) int
+
that, given an array A consisting of N integers containing daily prices of a stock share for a period of N consecutive days, returns the maximum possible profit from one transaction during this period. The function should return 0 if it was impossible to gain any profit.
+
For example, given array A consisting of six elements such that:
Find a maximum sum of a compact subsequence of array elements.
+
A non-empty array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P ≤ Q < N, is called a slice of array A. The sum of a slice (P, Q) is the total of A[P] + A[P+1] + ... + A[Q].
+
Write a function:
+
func Solution(A []int) int
+
that, given an array A consisting of N integers, returns the maximum sum of any slice of A.
(3, 4) is a slice of A that has sum 4,
+(2, 2) is a slice of A that has sum −6,
+(0, 1) is a slice of A that has sum 5,
+no other slice of A has sum greater than (0, 1).
+Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [1..1,000,000];
+each element of array A is an integer within the range [−1,000,000..1,000,000];
+the result will be an integer within the range [−2,147,483,648..2,147,483,647].
+
Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Find the maximum number of flags that can be set on mountain peaks.
+
A non-empty array A consisting of N integers is given.
+
A peak is an array element which is larger than its neighbours. More precisely, it is an index P such that 0 < P < N − 1 and A[P − 1] < A[P] > A[P + 1].
You are going on a trip to a range of mountains whose relative heights are represented by array A, as shown in a figure below. You have to choose how many flags you should take with you. The goal is to set the maximum number of flags on the peaks, according to certain rules.
+
+
Flags can only be set on peaks. What's more, if you take K flags, then the distance between any two flags should be greater than or equal to K. The distance between indices P and Q is the absolute value |P − Q|.
+
For example, given the mountain range represented by array A, above, with N = 12, if you take:
+
two flags, you can set them on peaks 1 and 5;
+three flags, you can set them on peaks 1, 5 and 10;
+four flags, you can set only three flags, on peaks 1, 5 and 10.
+You can therefore set a maximum of three flags in this case.
+
Write a function:
+
func Solution(A []int) int
+
that, given a non-empty array A of N integers, returns the maximum number of flags that can be set on the peaks of the array.
Find the minimal perimeter of any rectangle whose area equals N.
+
An integer N is given, representing the area of some rectangle.
+
The area of a rectangle whose sides are of length A and B is A B, and the perimeter is 2 (A + B).
+
The goal is to find the minimal perimeter of any rectangle whose area equals N. The sides of this rectangle should be only integers.
+
For example, given integer N = 30, rectangles of area 30 are:
+
(1, 30), with a perimeter of 62,
+(2, 15), with a perimeter of 34,
+(3, 10), with a perimeter of 26,
+(5, 6), with a perimeter of 22.
+Write a function:
+
func Solution(N int) int
+
that, given an integer N, returns the minimal perimeter of any rectangle whose area is exactly equal to N.
+
For example, given an integer N = 30, the function should return 22, as explained above.
+
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [1..1,000,000,000].
+
Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Divide an array into the maximum number of same-sized blocks, each of which should contain an index P such that A[P - 1] < A[P] > A[P + 1].
+
A non-empty array A consisting of N integers is given.
+
A peak is an array element which is larger than its neighbors. More precisely, it is an index P such that 0 < P < N − 1, A[P − 1] < A[P] and A[P] > A[P + 1].
We want to divide this array into blocks containing the same number of elements. More precisely, we want to choose a number K that will yield the following blocks:
+
A[0], A[1], ..., A[K − 1],
+A[K], A[K + 1], ..., A[2K − 1],
+...
+A[N − K], A[N − K + 1], ..., A[N − 1].
+What's more, every block should contain at least one peak. Notice that extreme elements of the blocks (for example A[K − 1] or A[K]) can also be peaks, but only if they have both neighbors (including one in an adjacent blocks).
+
The goal is to find the maximum number of blocks into which the array A can be divided.
+
Array A can be divided into blocks as follows:
+
one block (1, 2, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2). This block contains three peaks.
+two blocks (1, 2, 3, 4, 3, 4) and (1, 2, 3, 4, 6, 2). Every block has a peak.
+three blocks (1, 2, 3, 4), (3, 4, 1, 2), (3, 4, 6, 2). Every block has a peak. Notice in particular that the first block (1, 2, 3, 4) has a peak at A[3], because A[2] < A[3] > A[4], even though A[4] is in the adjacent block.
+However, array A cannot be divided into four blocks, (1, 2, 3), (4, 3, 4), (1, 2, 3) and (4, 6, 2), because the (1, 2, 3) blocks do not contain a peak. Notice in particular that the (4, 3, 4) block contains two peaks: A[3] and A[5].
+
The maximum number of blocks that array A can be divided into is three.
+
Write a function:
+
func Solution(A []int) int
+
that, given a non-empty array A consisting of N integers, returns the maximum number of blocks into which A can be divided.
+
If A cannot be divided into some number of blocks, the function should return 0.
Calculate the number of elements of an array that are not divisors(因數) of each element.
+
You are given an array A consisting of N integers.
+
For each number A[i] such that 0 ≤ i < N, we want to count the number of elements of the array that are not the divisors of A[i]. We say that these elements are non-divisors.
+
For example, consider integer N = 5 and array A such that:
Count the semiprime(半質數:兩個質數的乘積所得的自然數我們稱之為半質數) numbers in the given range [a..b]
+
A prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13.
+
A semiprime is a natural number that is the product of two (not necessarily distinct) prime numbers. The first few semiprimes are 4, 6, 9, 10, 14, 15, 21, 22, 25, 26.
+
You are given two non-empty arrays P and Q, each consisting of M integers. These arrays represent queries about the number of semiprimes within specified ranges.
+
Query K requires you to find the number of semiprimes within the range (P[K], Q[K]), where 1 ≤ P[K] ≤ Q[K] ≤ N.
+
For example, consider an integer N = 26 and arrays P, Q such that:
The number of semiprimes within each of these ranges is as follows:
+
(1, 26) is 10,
+(4, 10) is 4,
+(16, 20) is 0.
+Write a function:
+
func Solution(N int, P []int, Q []int) []int
+
that, given an integer N and two non-empty arrays P and Q consisting of M integers, returns an array consisting of M elements specifying the consecutive answers to all the queries.
+
For example, given an integer N = 26 and arrays P, Q such that:
the function should return the values [10, 4, 0], as explained above.
+
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [1..50,000];
+M is an integer within the range [1..30,000];
+each element of arrays P, Q is an integer within the range [1..N];
+P[i] ≤ Q[i].
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Check whether two numbers have the same prime divisors.
+
A prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13.
+
A prime D is called a prime divisor(質因數) of a positive integer P if there exists a positive integer K such that D * K = P. For example, 2 and 5 are prime divisors of 20.
+
You are given two positive integers N and M. The goal is to check whether the sets of prime divisors of integers N and M are exactly the same.
+
For example, given:
+
N = 15 and M = 75, the prime divisors are the same: {3, 5};
+N = 10 and M = 30, the prime divisors aren't the same: {2, 5} is not equal to {2, 3, 5};
+N = 9 and M = 5, the prime divisors aren't the same: {3} is not equal to {5}.
+Write a function:
+
func Solution(A []int, B []int) int
+
that, given two non-empty arrays A and B of Z integers, returns the number of positions K for which the prime divisors of A[K] and B[K] are exactly the same.
the function should return 1, because only one pair (15, 75) has the same set of prime divisors.
+
Write an efficient algorithm for the following assumptions:
+
Z is an integer within the range [1..6,000];
+each element of arrays A, B is an integer within the range [1..2,147,483,647].
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
The Fibonacci sequence is defined using the following recursive formula:
+
F(0) = 0
+F(1) = 1
+F(M) = F(M - 1) + F(M - 2) if M >= 2
+
A small frog wants to get to the other side of a river. The frog is initially located at one bank of the river (position −1) and wants to get to the other bank (position N). The frog can jump over any distance F(K), where F(K) is the K-th Fibonacci number. Luckily, there are many leaves on the river, and the frog can jump between the leaves, but only in the direction of the bank at position N.
+
The leaves on the river are represented in an array A consisting of N integers. Consecutive(連續的) elements of array A represent consecutive positions from 0 to N − 1 on the river. Array A contains only 0s and/or 1s:
+
0 represents a position without a leaf;
+1 represents a position containing a leaf.
+The goal is to count the minimum number of jumps in which the frog can get to the other side of the river (from position −1 to position N). The frog can jump between positions −1 and N (the banks of the river) and every position containing a leaf.
The frog can make three jumps of length F(5) = 5, F(3) = 2 and F(5) = 5.
+
Write a function:
+
func Solution(A []int) int
+
that, given an array A consisting of N integers, returns the minimum number of jumps by which the frog can get to the other side of the river. If the frog cannot reach the other side of the river, the function should return −1.
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [0..100,000];
+each element of array A is an integer that can have one of the following values: 0, 1.
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
A non-empty array A consisting of N numbers is given. The array is sorted in non-decreasing order. The absolute distinct count of this array is the number of distinct absolute values among the elements of the array.
+
For example, consider array A such that:
+
A[0] = -5
+ A[1] = -3
+ A[2] = -1
+ A[3] = 0
+ A[4] = 3
+ A[5] = 6
+The absolute distinct count of this array is 5, because there are 5 distinct absolute values among the elements of this array, namely 0, 1, 3, 5 and 6.
+
Write a function:
+
func Solution(A []int) int
+
that, given a non-empty array A consisting of N numbers, returns absolute distinct count of array A.
Write an efficient algorithm for the following assumptions:
+
N is an integer within the range [1..100,000];
+each element of array A is an integer within the range [−2,147,483,648..2,147,483,647];
+array A is sorted in non-decreasing order.
+Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Given a package with a weight limit limit and an array arr of item weights, implement a function
+getIndicesOfItemWeights that finds two items whose sum of weights equals the weight limit. The function should
+return a pair [i, j] of the indices of the item weights, ordered such that i > j. If such a pair doesn’t exist, return
+an empty array.
+input: arr = [4, 6, 10, 15, 16], lim = 21
+output: [3, 1] # since these are the indices of the weights 6 and 15 whose sum equals to 21
Given a string, find the length of the longest substring without repeating characters.
+
Example 1:
+
Input: "abcabcbb"
+Output: 3
+Explanation: The answer is "abc", with the length of 3.
+
+
Example 2:
+
Input: "bbbbb"
+Output: 1
+Explanation: The answer is "b", with the length of 1.
+
+
Example 3:
+
Input: "pwwkew"
+Output: 3
+Explanation: The answer is "wke", with the length of 3.
+Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
+
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
+
Note:
+
The solution set must not contain duplicate triplets.
+
Example:
+
Given array nums = [-1, 0, 1, 2, -1, -4],
+
+A solution set is:
+[
+ [-1, 0, 1],
+ [-1, -1, 2]
+]
+
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
+
An input string is valid if:
+
Open brackets must be closed by the same type of brackets.
+Open brackets must be closed in the correct order.
+Every close bracket has a corresponding open bracket of the same type.
+
Example 1:
+
Input: s = "()"
+Output: true
+Example 2:
+
Input: s = "()[]{}"
+Output: true
+Example 3:
+
Input: s = "(]"
+Output: false
+
Constraints:
+
1 <= s.length <= 104
+s consists of parentheses only '()[]{}'.
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
+
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
+
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
+
Example 1:
+
Given nums = [3,2,2,3], val = 3,
+
+Your function should return length = 2, with the first two elements of nums being 2.
+
+It doesn't matter what you leave beyond the returned length.
+
+
Example 2:
+
Given nums = [0,1,2,2,3,0,4,2], val = 2,
+
+Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
+
+Note that the order of those five elements can be arbitrary.
+
+It doesn't matter what values are set beyond the returned length.
+
+
Clarification:
+
Confused why the returned value is an integer but your answer is an array?
+
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
+
Internally you can think of this:
+
// nums is passed in by reference. (i.e., without making a copy)
+int len = removeElement(nums, val);
+
+// any modification to nums in your function would be known by the caller.
+// using the length returned by your function, it prints the first len elements.
+for (int i = 0; i < len; i++) {
+ print(nums[i]);
+}
+
+
題目大意
+
給定一個數組 nums 和一個數值 val,將數組中所有等於 val 的元素刪除,並返回剩餘的元素個數。
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
+
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
+
Note: You are not suppose to use the library's sort function for this problem.
+
Example 1:
+
Input: [2,0,2,1,1,0]
+Output: [0,0,1,1,2,2]
+
Follow up:
+
+
A rather straight forward solution is a two-pass algorithm using counting sort. First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
+
Could you come up with a one-pass algorithm using only constant space?
+
+
+
給定一個包含紅色、白色和藍色,一共 n 個元素的數組,原地對它們進行排序,使得相同顏色的元素相鄰,並按照紅色、白色、藍色順序排列。
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
+
Note:
+
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
+
Example:
+
Input:
+nums1 = [1,2,3,0,0,0], m = 3
+nums2 = [2,5,6], n = 3
+
Output: [1,2,2,3,5,6]
+Constraints:
+
-10^9 <= nums1[i], nums2[i] <= 10^9
+nums1.length == m + n
+nums2.length == n
You are given an array prices where prices[i] is the price of a given stock on the ith day.
+
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
+
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
+
Example 1:
+
Input: prices = [7,1,5,3,6,4]
+Output: 5
+Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
+Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
+Example 2:
+
Input: prices = [7,6,4,3,1]
+Output: 0
+Explanation: In this case, no transactions are done and the max profit = 0.
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
+
Given a string s, return true if it is a palindrome, or false otherwise.
+
Example 1:
+
Input: s = "A man, a plan, a canal: Panama"
+Output: true
+Explanation: "amanaplanacanalpanama" is a palindrome.
+Example 2:
+
Input: s = "race a car"
+Output: false
+Explanation: "raceacar" is not a palindrome.
+Example 3:
+
Input: s = " "
+Output: true
+Explanation: s is an empty string "" after removing non-alphanumeric characters.
+Since an empty string reads the same forward and backward, it is a palindrome.
+
Constraints:
+
1 <= s.length <= 2 * 105
+s consists only of printable ASCII characters.
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
+
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.
+
Do not modify the linked list.
+
Example 1:
+
+
Input: head = [3,2,0,-4], pos = 1
+Output: tail connects to node index 1
+Explanation: There is a cycle in the linked list, where tail connects to the second node.
+
Example 2:
+
+
Input: head = [1,2], pos = 0
+Output: tail connects to node index 0
+Explanation: There is a cycle in the linked list, where tail connects to the first node.
+
Example 3:
+
+
Input: head = [1], pos = -1
+Output: no cycle
+Explanation: There is no cycle in the linked list.
+
Constraints:
+
+
The number of the nodes in the list is in the range [0, 104].
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 < numbers.length.
+
Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.
+
The tests are generated such that there is exactly one solution. You may not use the same element twice.
+
Your solution must use only constant extra space.
+
Example 1:
+
Input: numbers = [2,7,11,15], target = 9
+Output: [1,2]
+Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
+Example 2:
+
Input: numbers = [2,3,4], target = 6
+Output: [1,3]
+Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
+Example 3:
+
Input: numbers = [-1,0], target = -1
+Output: [1,2]
+Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].
+
Constraints:
+
2 <= numbers.length <= 3 * 104
+-1000 <= numbers[i] <= 1000
+numbers is sorted in non-decreasing order.
+-1000 <= target <= 1000
+The tests are generated such that there is exactly one solution.
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
+
Example 1:
+
Input: s = 7, nums = [2,3,1,2,4,3]
+Output: 2
+Explanation: the subarray [4,3] has the minimal length under the problem constraint.
+
+
Input: s = 4, nums = [1,4,4]
+Output: 1
+
Input: s = 11, nums = [1,1,1,1,1,1,1,1]
+Output: 0
+
Follow up:
+
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
package validanagram
+
+func IsAnagram(s string, t string) bool {
+ if len(s) != len(t) {
+ return false
+ }
+
+ record := make(map[rune]int, len(s))
+
+ for _, v := range s {
+ record[v]++
+ }
+ for _, v := range t {
+ record[v]--
+ if record[v] < 0 {
+ return false
+ }
+ }
+ return true
+}
+
+func IsAnagram2(s string, t string) bool {
+ if len(s) != len(t) {
+ return false
+ }
+
+ record := make(map[rune]int, len(s))
+
+ for _, v := range s {
+ record[v]++
+ }
+ for _, v := range t {
+ record[v]--
+ }
+
+ for _, v := range record {
+ if v != 0 {
+ return false
+ }
+ }
+ return true
+}
+
Given an integer array nums, return the length of the longest strictly increasing subsequence.
+
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
+
Example 1:
+
Input: nums = [10,9,2,5,3,7,101,18]
+Output: 4
+Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
+
Example 2:
+
Input: nums = [0,1,0,3,2,3]
+Output: 4
+
Example 3:
+
Input: nums = [7,7,7,7,7,7,7]
+Output: 1
+
Constraints:
+
+
1 <= nums.length <= 2500
+
-104 <= nums[i] <= 104
+
+
Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?
A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.
+
Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h)) are called minimum height trees (MHTs).
+
Return a list of all MHTs' root labels. You can return the answer in any order.
+
The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
+
Example 1:
+
+
Input: n = 4, edges = [[1,0],[1,2],[1,3]]
+Output: [1]
+Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
+
Example 2:
+
+
Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
+Output: [3,4]
+
Constraints:
+
+
1 <= n <= 2 * 104
+
edges.length == n - 1
+
0 <= ai, bi < n
+
ai != bi
+
All the pairs (ai, bi) are distinct.
+
The given input is guaranteed to be a tree and there will be no repeated edges.
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
+
Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
+
You may assume that you have an infinite number of each kind of coin.
1 <= nums.length <= 105
+-104 <= nums[i] <= 104
+k is in the range [1, the number of unique elements in the array].
+It is guaranteed that the answer is unique.
+
Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
+
Seen this question in a real interview before? 1/4
You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.
+
One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.
+
Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).
+
Note: You cannot rotate an envelope.
+
Example 1:
+
Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
+Output: 3
+Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
+
package russiandollenvelopes
+
+import (
+ longestincreasingsubsequence "LeetcodeGolang/Leetcode/0300.Longest-Increasing-Subsequence"
+ "sort"
+)
+
+type sortEnvelopes [][]int
+
+func (s sortEnvelopes) Len() int {
+ return len(s)
+}
+
+func (s sortEnvelopes) Less(i, j int) bool {
+ if s[i][0] == s[j][0] {
+ // 遇到w相同的情況, 則按照高度進行降序排序
+ return s[i][1] > s[j][1]
+ }
+ // 對寬度w進行升序排序
+ return s[i][0] < s[j][0]
+}
+
+func (s sortEnvelopes) Swap(i, j int) {
+ s[i], s[j] = s[j], s[i]
+}
+
+func MaxEnvelopes(envelopes [][]int) int {
+ // 先對寬度w進行升序排序, 如果遇到w相同的情況, 則按照高度進行降序排序.
+ sort.Sort(sortEnvelopes(envelopes))
+ // fmt.Println(envelopes)
+
+ // 所有的h最為一個array, 對此array做 最長遞增子序列(Longest Increasing Subsequence, LIS)的長度就是答案
+ height := make([]int, len(envelopes))
+ for i := 0; i < len(envelopes); i++ {
+ height[i] = envelopes[i][1]
+ }
+
+ // DP + 二分搜尋:patience sorting. O(nlogn)
+ return longestincreasingsubsequence.LengthOfLISPatience(height)
+}
+
+func MaxEnvelopes2(envelopes [][]int) int {
+ // 先對寬度w進行升序排序, 如果遇到w相同的情況, 則按照高度進行降序排序.
+ sort.Sort(sortEnvelopes(envelopes))
+ // fmt.Println(envelopes)
+
+ // 最長遞增子序列(Longest Increasing Subsequence, LIS)的長度就是答案
+ dp := []int{}
+ for _, e := range envelopes {
+ left, right := 0, len(dp)
+ for left < right {
+ mid := left + (right-left)/2
+ if dp[mid] > e[1] {
+ // 現在的牌比堆小, 所小範圍
+ right = mid
+ } else if dp[mid] < e[1] {
+ // 現在的牌比堆大
+ left = mid + 1
+ } else {
+ right = mid
+ }
+ }
+
+ // 沒有找到堆, 建立一個新的堆
+ if left == len(dp) {
+ dp = append(dp, e[1])
+ }
+
+ // 再把這張牌放在堆的頂端
+ dp[left] = e[1]
+ }
+
+ return len(dp)
+}
+
+/*
+func Sort(data Interface) {
+ n := data.Len()
+ quickSort(data, 0, n, maxDepth(n))
+}
+type Interface interface {
+ // Len is the number of elements in the collection.
+ Len() int
+
+ // Less reports whether the element with index i
+ // must sort before the element with index j.
+ //
+ // If both Less(i, j) and Less(j, i) are false,
+ // then the elements at index i and j are considered equal.
+ // Sort may place equal elements in any order in the final result,
+ // while Stable preserves the original input order of equal elements.
+ //
+ // Less must describe a transitive ordering:
+ // - if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well.
+ // - if both Less(i, j) and Less(j, k) are false, then Less(i, k) must be false as well.
+ //
+ // Note that floating-point comparison (the < operator on float32 or float64 values)
+ // is not a transitive ordering when not-a-number (NaN) values are involved.
+ // See Float64Slice.Less for a correct implementation for floating-point values.
+ Less(i, j int) bool
+
+ // Swap swaps the elements with indexes i and j.
+ Swap(i, j int)
+}
+*/
+
+
go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=.
+goos: darwin
+goarch: amd64
+pkg: LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes
+cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
+BenchmarkMaxEnvelopes-8 9067520 167.0 ns/op 88 B/op 3 allocs/op
+BenchmarkMaxEnvelopes2-8 6726646 214.9 ns/op 80 B/op 4 allocs/op
+PASS
+ok LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes 6.237s
+
+
+
+
+
+
+
+
+
+
results matching ""
+
+
+
+
+
+
No results matching ""
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Leetcode/0354.Russian-Doll-Envelopes/main.go b/Leetcode/0354.Russian-Doll-Envelopes/main.go
new file mode 100644
index 000000000..8ffb917d7
--- /dev/null
+++ b/Leetcode/0354.Russian-Doll-Envelopes/main.go
@@ -0,0 +1,105 @@
+package russiandollenvelopes
+
+import (
+ longestincreasingsubsequence "LeetcodeGolang/Leetcode/0300.Longest-Increasing-Subsequence"
+ "sort"
+)
+
+type sortEnvelopes [][]int
+
+func (s sortEnvelopes) Len() int {
+ return len(s)
+}
+
+func (s sortEnvelopes) Less(i, j int) bool {
+ if s[i][0] == s[j][0] {
+ // ้ๅฐw็ธๅ็ๆ ๆณ, ๅๆ็ ง้ซๅบฆ้ฒ่ก้ๅบๆๅบ
+ return s[i][1] > s[j][1]
+ }
+ // ๅฐๅฏฌๅบฆw้ฒ่กๅๅบๆๅบ
+ return s[i][0] < s[j][0]
+}
+
+func (s sortEnvelopes) Swap(i, j int) {
+ s[i], s[j] = s[j], s[i]
+}
+
+func MaxEnvelopes(envelopes [][]int) int {
+ // ๅ ๅฐๅฏฌๅบฆw้ฒ่กๅๅบๆๅบ, ๅฆๆ้ๅฐw็ธๅ็ๆ ๆณ, ๅๆ็ ง้ซๅบฆ้ฒ่ก้ๅบๆๅบ.
+ sort.Sort(sortEnvelopes(envelopes))
+ // fmt.Println(envelopes)
+
+ // ๆๆ็hๆ็บไธๅarray, ๅฐๆญคarrayๅ ๆ้ท้ๅขๅญๅบๅ(Longest Increasing Subsequence, LIS)็้ทๅบฆๅฐฑๆฏ็ญๆก
+ height := make([]int, len(envelopes))
+ for i := 0; i < len(envelopes); i++ {
+ height[i] = envelopes[i][1]
+ }
+
+ // DP + ไบๅๆๅฐ:patience sorting. O(nlogn)
+ return longestincreasingsubsequence.LengthOfLISPatience(height)
+}
+
+func MaxEnvelopes2(envelopes [][]int) int {
+ // ๅ ๅฐๅฏฌๅบฆw้ฒ่กๅๅบๆๅบ, ๅฆๆ้ๅฐw็ธๅ็ๆ ๆณ, ๅๆ็ ง้ซๅบฆ้ฒ่ก้ๅบๆๅบ.
+ sort.Sort(sortEnvelopes(envelopes))
+ // fmt.Println(envelopes)
+
+ // ๆ้ท้ๅขๅญๅบๅ(Longest Increasing Subsequence, LIS)็้ทๅบฆๅฐฑๆฏ็ญๆก
+ dp := []int{}
+ for _, e := range envelopes {
+ left, right := 0, len(dp)
+ for left < right {
+ mid := left + (right-left)/2
+ if dp[mid] > e[1] {
+ // ็พๅจ็็ๆฏๅ ๅฐ, ๆๅฐ็ฏๅ
+ right = mid
+ } else if dp[mid] < e[1] {
+ // ็พๅจ็็ๆฏๅ ๅคง
+ left = mid + 1
+ } else {
+ right = mid
+ }
+ }
+
+ // ๆฒๆๆพๅฐๅ , ๅปบ็ซไธๅๆฐ็ๅ
+ if left == len(dp) {
+ dp = append(dp, e[1])
+ }
+
+ // ๅๆ้ๅผต็ๆพๅจๅ ็้ ็ซฏ
+ dp[left] = e[1]
+ }
+
+ return len(dp)
+}
+
+/*
+func Sort(data Interface) {
+ n := data.Len()
+ quickSort(data, 0, n, maxDepth(n))
+}
+type Interface interface {
+ // Len is the number of elements in the collection.
+ Len() int
+
+ // Less reports whether the element with index i
+ // must sort before the element with index j.
+ //
+ // If both Less(i, j) and Less(j, i) are false,
+ // then the elements at index i and j are considered equal.
+ // Sort may place equal elements in any order in the final result,
+ // while Stable preserves the original input order of equal elements.
+ //
+ // Less must describe a transitive ordering:
+ // - if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well.
+ // - if both Less(i, j) and Less(j, k) are false, then Less(i, k) must be false as well.
+ //
+ // Note that floating-point comparison (the < operator on float32 or float64 values)
+ // is not a transitive ordering when not-a-number (NaN) values are involved.
+ // See Float64Slice.Less for a correct implementation for floating-point values.
+ Less(i, j int) bool
+
+ // Swap swaps the elements with indexes i and j.
+ Swap(i, j int)
+}
+*/
diff --git a/Leetcode/0354.Russian-Doll-Envelopes/main_test.go b/Leetcode/0354.Russian-Doll-Envelopes/main_test.go
new file mode 100644
index 000000000..fd3da39ca
--- /dev/null
+++ b/Leetcode/0354.Russian-Doll-Envelopes/main_test.go
@@ -0,0 +1,59 @@
+package russiandollenvelopes
+
+import "testing"
+
+var tests = []struct {
+ arg1 [][]int
+ want int
+}{
+ {
+ [][]int{{5, 4}, {6, 4}, {6, 7}, {2, 3}},
+ 3,
+ },
+ {
+ [][]int{{1, 1}, {1, 1}, {1, 1}},
+ 1,
+ },
+}
+
+func TestMaxEnvelopes(t *testing.T) {
+ for _, tt := range tests {
+ if got := MaxEnvelopes(tt.arg1); got != tt.want {
+ t.Errorf("got = %v, want = %v", got, tt.want)
+ }
+ }
+}
+
+func TestMaxEnvelopes2(t *testing.T) {
+ for _, tt := range tests {
+ if got := MaxEnvelopes2(tt.arg1); got != tt.want {
+ t.Errorf("got = %v, want = %v", got, tt.want)
+ }
+ }
+}
+
+func BenchmarkMaxEnvelopes(b *testing.B) {
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ MaxEnvelopes(tests[0].arg1)
+ }
+}
+
+func BenchmarkMaxEnvelopes2(b *testing.B) {
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ MaxEnvelopes2(tests[0].arg1)
+ }
+}
+
+/*
+go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=.
+goos: darwin
+goarch: amd64
+pkg: LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes
+cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
+BenchmarkMaxEnvelopes-8 9067520 167.0 ns/op 88 B/op 3 allocs/op
+BenchmarkMaxEnvelopes2-8 6726646 214.9 ns/op 80 B/op 4 allocs/op
+PASS
+ok LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes 6.237s
+*/
diff --git a/Leetcode/0380.Insert-Delete-GetRandom-O1/index.html b/Leetcode/0380.Insert-Delete-GetRandom-O1/index.html
new file mode 100644
index 000000000..a1fdfc189
--- /dev/null
+++ b/Leetcode/0380.Insert-Delete-GetRandom-O1/index.html
@@ -0,0 +1,3893 @@
+
+
+
+
+
+
+ 380. Insert Delete GetRandom O(1) ยท Kimi's LeetcodeGolang Notes
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
RandomizedSet() Initializes the RandomizedSet object.
+bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
+bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
+int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.
+You must implement the functions of the class such that each function works in average O(1) time complexity.
Explanation
+RandomizedSet randomizedSet = new RandomizedSet();
+randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
+randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
+randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
+randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
+randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
+randomizedSet.insert(2); // 2 was already in the set, so return false.
+randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
+
Constraints:
+
-231 <= val <= 231 - 1
+At most 2 * 105 calls will be made to insert, remove, and getRandom.
+There will be at least one element in the data structure when getRandom is called.
RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element.
+
Implement the RandomizedCollection class:
+
RandomizedCollection() Initializes the empty RandomizedCollection object.
+bool insert(int val) Inserts an item val into the multiset, even if the item is already present. Returns true if the item is not present, false otherwise.
+bool remove(int val) Removes an item val from the multiset if present. Returns true if the item is present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them.
+int getRandom() Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of the same values the multiset contains.
+You must implement the functions of the class such that each function works on average O(1) time complexity.
+
Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection.
Explanation
+RandomizedCollection randomizedCollection = new RandomizedCollection();
+randomizedCollection.insert(1); // return true since the collection does not contain 1.
+ // Inserts 1 into the collection.
+randomizedCollection.insert(1); // return false since the collection contains 1.
+ // Inserts another 1 into the collection. Collection now contains [1,1].
+randomizedCollection.insert(2); // return true since the collection does not contain 2.
+ // Inserts 2 into the collection. Collection now contains [1,1,2].
+randomizedCollection.getRandom(); // getRandom should:
+ // - return 1 with probability 2/3, or
+ // - return 2 with probability 1/3.
+randomizedCollection.remove(1); // return true since the collection contains 1.
+ // Removes 1 from the collection. Collection now contains [1,2].
+randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.
+
Constraints:
+
-231 <= val <= 231 - 1
+At most 2 * 105 calls in total will be made to insert, remove, and getRandom.
+There will be at least one element in the data structure when getRandom is called.
Facebook, Microsoft, Apple
+Given an integer n, return a string array answer (1-indexed) where:
+
answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
+answer[i] == "Fizz" if i is divisible by 3.
+answer[i] == "Buzz" if i is divisible by 5.
+answer[i] == i (as a string) if none of the above conditions are true.
+
Example 1:
+
Input: n = 3
+Output: ["1","2","Fizz"]
+Example 2:
+
Input: n = 5
+Output: ["1","2","Fizz","4","Buzz"]
+Example 3:
+
Input: n = 15
+Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
+
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
+
Example 1:
+
Input: s = "cbaebabacd", p = "abc"
+Output: [0,6]
+Explanation:
+The substring with start index = 0 is "cba", which is an anagram of "abc".
+The substring with start index = 6 is "bac", which is an anagram of "abc".
+
Example 2:
+
Input: s = "abab", p = "ab"
+Output: [0,1,2]
+Explanation:
+The substring with start index = 0 is "ab", which is an anagram of "ab".
+The substring with start index = 1 is "ba", which is an anagram of "ab".
+The substring with start index = 2 is "ab", which is an anagram of "ab".
+
Constraints:
+
1 <= s.length, p.length <= 3 * 104
+s and p consist of lowercase English letters.
+
題目大意
+
找所有字母異位詞, 就像全排列
+給定一個字符串 S 和非空的字符串 P, 找到 S 中所有是 P 得排列, 並返回他的起始 index
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
+
F(0) = 0, F(1) = 1
+F(n) = F(n - 1) + F(n - 2), for n > 1.
+
// --- Directions
+// Print out the n-th entry in the fibonacci series.
+// The fibonacci series is an ordering of numbers where
+// each number is the sum of the preceeding two.
+// For example, the sequence
+// [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
+// forms the first ten entries of the fibonacci series.
+// Example:
+// fib(4) === 3
+
+package fibonaccinumber
+
+import "math"
+
+// Fib : iterative 迴圈 O(n) . 空間複雜 O(n). 自底向上的記憶化搜索
+func FibIterative(n int) int {
+ var result = []int{0, 1}
+
+ for i := 2; i
Given a string s, find the longest palindromic subsequence's length in s.
+
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
+
Example 1:
+
Input: s = "bbbab"
+Output: 4
+Explanation: One possible longest palindromic subsequence is "bbbb".
+
Example 2:
+
Input: s = "cbbd"
+Output: 2
+Explanation: One possible longest palindromic subsequence is "bb".
+
You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
+
The area of an island is the number of cells with a value 1 in the island.
+
Return the maximum area of an island in grid. If there is no island, return 0.
+
Example 1:
+
+
Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
+Output: 6
+Explanation: The answer is not 11, because the island must be connected 4-directionally.
+
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
+
Implement KthLargest class:
+
KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
+int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream.
1 <= k <= 104
+0 <= nums.length <= 104
+-104 <= nums[i] <= 104
+-104 <= val <= 104
+At most 104 calls will be made to add.
+It is guaranteed that there will be at least k elements in the array when you search for the kth element.
+Accepted
+479.1K
+Submissions
+846.4K
+Acceptance Rate
+56.6%
+
題目大意
+
設計一個找到數據流中第 k 大元素的類(class)。 注意是排序後的第 k 大元素,不是第 k 個不同的元素。 請實現 KthLargest 類:
+
+
KthLargest(int k, int[] nums) 使用整數 k 和整數流 nums 初始化物件。
+
int add(int val) 將 val 插入數據流 nums 後,返回當前數據流中第 k 大的元素。
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
+
You must write an algorithm with O(log n) runtime complexity.
+
Example 1:
+
Input: nums = [-1,0,3,5,9,12], target = 9
+Output: 4
+Explanation: 9 exists in nums and its index is 4
+
Example 2:
+
Input: nums = [-1,0,3,5,9,12], target = 2
+Output: -1
+Explanation: 2 does not exist in nums so return -1
+
Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emailsrepresenting emails of the account.
+
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email that is common to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
+
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.
+
Example 1:
+
Input:
+accounts = [["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"], ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"]]
+Output: [["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'], ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"]]
+Explanation:
+The first and third John's are the same person as they have the common email "johnsmith@mail.com".
+The second John and Mary are different people as none of their email addresses are used by other accounts.
+We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'],
+['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.
+
Note:
+
+
The length of accounts will be in the range [1, 1000].
+
The length of accounts[i] will be in the range [1, 10].
+
The length of accounts[i][j] will be in the range [1, 30].
An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.
+
You are also given three integers sr,sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].
+
To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color.
+
Return the modified image after performing the flood fill.
+
Example 1:
+
+
Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2
+Output: [[2,2,2],[2,2,0],[2,0,1]]
+Explanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
+Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
+
+
Example 2:
+
Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0
+Output: [[0,0,0],[0,0,0]]
+Explanation: The starting pixel is already colored 0, so no changes are made to the image.
+
package floodfill
+
+// DFS
+func FloodFill(image [][]int, sr int, sc int, color int) [][]int {
+ oldColor := image[sr][sc]
+ if color == oldColor {
+ return image
+ }
+ dfsfill(image, sr, sc, oldColor, color)
+ return image
+}
+
+func dfsfill(image [][]int, row, col, oldColor, newColor int) {
+ // Check if the current pixel is out of bounds or does not have the old color
+ if row < 0 || row >= len(image) || col < 0 || col >= len(image[0]) || image[row][col] != oldColor {
+ return
+ }
+
+ // Update the current pixel with the new color
+ image[row][col] = newColor
+
+ // Recursively perform flood fill on the adjacent pixels
+ dfsfill(image, row-1, col, oldColor, newColor) // Up
+ dfsfill(image, row+1, col, oldColor, newColor) // Down
+ dfsfill(image, row, col-1, oldColor, newColor) // Left
+ dfsfill(image, row, col+1, oldColor, newColor) // Right
+}
+
+type Point struct {
+ row, col int
+}
+
+func FloodFillBFS(image [][]int, sr int, sc int, newColor int) [][]int {
+ // Check if the starting point is out of bounds or already has the new color
+ if sr < 0 || sr >= len(image) || sc < 0 || sc >= len(image[0]) || image[sr][sc] == newColor {
+ return image
+ }
+
+ // Get the old color at the starting point
+ oldColor := image[sr][sc]
+
+ // Create a queue and enqueue the starting point
+ queue := []Point{{sr, sc}}
+
+ // Define the directions (up, down, left, right)
+ directions := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}
+
+ // Perform BFS
+ for len(queue) > 0 {
+ // Dequeue a point from the queue
+ point := queue[0]
+ queue = queue[1:]
+
+ // Update the point with the new color
+ image[point.row][point.col] = newColor
+
+ // Explore the neighboring pixels
+ for _, dir := range directions {
+ newRow, newCol := point.row+dir[0], point.col+dir[1]
+
+ // Check if the neighboring pixel is within bounds and has the old color
+ if newRow >= 0 && newRow < len(image) && newCol >= 0 && newCol < len(image[0]) && image[newRow][newCol] == oldColor {
+ // Enqueue the neighboring pixel
+ queue = append(queue, Point{newRow, newCol})
+ }
+ }
+ }
+
+ return image
+}
+
You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.
+
You can either start from the step with index 0, or the step with index 1.
+
Return the minimum cost to reach the top of the floor.
+
Example 1:
+
Input: cost = [10,15,20]
+Output: 15
+Explanation: You will start at index 1.
+
+
Pay 15 and climb two steps to reach the top.
+The total cost is 15.
+Example 2:
+
+
Input: cost = [1,100,1,1,1,100,1,1,100,1]
+Output: 6
+Explanation: You will start at index 0.
+
+
Pay 1 and climb two steps to reach index 2.
+
Pay 1 and climb two steps to reach index 4.
+
Pay 1 and climb two steps to reach index 6.
+
Pay 1 and climb one step to reach index 7.
+
Pay 1 and climb two steps to reach index 9.
+
Pay 1 and climb one step to reach the top.
+The total cost is 6.
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.
+
The lock initially starts at '0000', a string representing the state of the 4 wheels.
+
You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
+
Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
+
Example 1:
+
Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
+Output: 6
+Explanation:
+A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
+Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,
+because the wheels of the lock become stuck after the display becomes the dead end "0102".
+
Example 2:
+
Input: deadends = ["8888"], target = "0009"
+Output: 1
+Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009".
+
Example 3:
+
Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
+Output: -1
+Explanation: We cannot reach the target without getting stuck.
+
You are given an array of integers stones where stones[i] is the weight of the ith stone.
+
We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is:
+
If x == y, both stones are destroyed, and
+If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.
+At the end of the game, there is at most one stone left.
+
Return the weight of the last remaining stone. If there are no stones left, return 0.
+
Example 1:
+
Input: stones = [2,7,4,1,8,1]
+Output: 1
+Explanation:
+We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
+we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
+we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
+we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.
+Example 2:
+
Input: stones = [1]
+Output: 1
+
Constraints:
+
1 <= stones.length <= 30
+1 <= stones[i] <= 1000
+
題目大意
+
有一個集合 stones,每個 stone 的重量由正整數表示。
+每次可以選擇兩個不同的石頭,將它們一起粉碎,然後得到一個新的石頭,其重量為兩者之差。
+你需要重複這個過程,直到集合中只剩下一個石頭,或者集合中沒有石頭為止。
+在這個過程中,找到可能的最後一顆石頭的重量。如果集合中沒有石頭,則返回 0。
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
+
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
+
For example, "ace" is a subsequence of "abcde".
+A common subsequence of two strings is a subsequence that is common to both strings.
+
Example 1:
+
Input: text1 = "abcde", text2 = "ace"
+Output: 3
+Explanation: The longest common subsequence is "ace" and its length is 3.
+
+
Example 2:
+
Input: text1 = "abc", text2 = "abc"
+Output: 3
+Explanation: The longest common subsequence is "abc" and its length is 3.
+
+
Example 3:
+
Input: text1 = "abc", text2 = "def"
+Output: 0
+Explanation: There is no such common subsequence, so the result is 0.
+
+
Constraints:
+
+
1 <= text1.length, text2.length <= 1000
+
text1 and text2 consist of only lowercase English characters.
printFizz that prints the word "fizz" to the console,
+printBuzz that prints the word "buzz" to the console,
+printFizzBuzz that prints the word "fizzbuzz" to the console, and
+printNumber that prints a given integer to the console.
+You are given an instance of the class FizzBuzz that has four functions: fizz, buzz, fizzbuzz and number. The same instance of FizzBuzz will be passed to four different threads:
+
Thread A: calls fizz() that should output the word "fizz".
+Thread B: calls buzz() that should output the word "buzz".
+Thread C: calls fizzbuzz() that should output the word "fizzbuzz".
+Thread D: calls number() that should only output the integers.
+Modify the given class to output the series [1, 2, "fizz", 4, "buzz", ...] where the ith token (1-indexed) of the series is:
+
"fizzbuzz" if i is divisible by 3 and 5,
+"fizz" if i is divisible by 3 and not 5,
+"buzz" if i is divisible by 5 and not 3, or
+i if i is not divisible by 3 or 5.
+Implement the FizzBuzz class:
+
FizzBuzz(int n) Initializes the object with the number n that represents the length of the sequence that should be printed.
+void fizz(printFizz) Calls printFizz to output "fizz".
+void buzz(printBuzz) Calls printBuzz to output "buzz".
+void fizzbuzz(printFizzBuzz) Calls printFizzBuzz to output "fizzbuzz".
+void number(printNumber) Calls printnumber to output the numbers.
+
Example 1:
+
Input: n = 15
+Output: [1,2,"fizz",4,"buzz","fizz",7,8,"fizz","buzz",11,"fizz",13,14,"fizzbuzz"]
+Example 2: