Цена за 48 часов в ленте | 400,00 |
Цена за 1 час закрепления | N/A |
Взаимопиар | Нет |
Дополнительные условия рекламы | Отсутствуют |
Input: n = 5
Output: 5
Explanation:
Here are the non-negative integers <= 5 with their corresponding binary representations:
0 : 0
1 : 1
2 : 10
3 : 11
4 : 100
5 : 101
Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.
class Solution {
fun findIntegers(num: Int): Int {
var count = 0
for (i in 0..num) {
if (check(i)) {
count++
}
}
return count
}
fun check(n: Int): Boolean {
var i = 31
while (i > 0) {
if ((n and (1 shl i)) != 0 && (n and (1 shl (i - 1))) != 0) {
return false
}
i--
}
return true
}
}
Input: nums = [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].
class Solution {
fun findLHS(nums: IntArray): Int {
val count = mutableMapOf()
var res = 0
for (num in nums) {
count[num] = count.getOrDefault(num, 0) + 1
if (count.containsKey(num + 1)) {
res = Math.max(res, count[num]!! + count[num + 1]!!)
}
if (count.containsKey(num - 1)) {
res = Math.max(res, count[num]!! + count[num - 1]!!)
}
}
return res
}
}
Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]
Output: ["Shogun"]
Explanation: The only common string is "Shogun".
class Solution {
fun findRestaurant(list1: Array, list2: Array ): Array {
val map = mutableMapOf>()
for (i in list1.indices) {
for (j in list2.indices) {
if (list1[i] == list2[j]) {
if (!map.containsKey(i + j)) {
map[i + j] = mutableListOf()
}
map[i + j]!!.add(list1[i])
}
}
}
val minIndexSum = map.keys.minOrNull()!!
return map[minIndexSum]!!.toTypedArray()
}
}
Input: m = 3, n = 3, ops = [[2,2],[3,3]]
Output: 4
Explanation: The maximum integer in M is 2, and there are four of it in M. So return 4.
class Solution {
fun maxCount(m: Int, n: Int, ops: Array): Int {
var minA = m
var minB = n
for (op in ops) {
minA = minOf(minA, op[0])
minB = minOf(minB, op[1])
}
return minA * minB
}
}
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: true
class Solution {
fun dist(p1: IntArray, p2: IntArray): Int {
return (p2[1] - p1[1]) * (p2[1] - p1[1]) + (p2[0] - p1[0]) * (p2[0] - p1[0])
}
fun check(p1: IntArray, p2: IntArray, p3: IntArray, p4: IntArray): Boolean {
return dist(p1, p2) > 0 &&
dist(p1, p2) == dist(p2, p3) &&
dist(p2, p3) == dist(p3, p4) &&
dist(p3, p4) == dist(p4, p1) &&
dist(p1, p3) == dist(p2, p4)
}
fun validSquare(p1: IntArray, p2: IntArray, p3: IntArray, p4: IntArray): Boolean {
return check(p1, p2, p3, p4) ||
check(p1, p3, p2, p4) ||
check(p1, p2, p4, p3)
}
}
Input: expression = "-1/2+1/2+1/3"
Output: "1/3"
class Solution {
fun fractionAddition(expression: String): String {
val sign = mutableListOf()
if (expression[0] != '-') sign.add('+')
for (char in expression) {
if (char == '+' || char == '-') sign.add(char)
}
val fractions = expression.split(Regex("(?=[+-])"))
var prevNum = 0
var prevDen = 1
var i = 0
for (sub in fractions) {
if (sub.isEmpty()) continue
val (num, den) = sub.split('/').map { it.toInt() }
val g = gcd(prevDen, den)
if (sign[i] == '+') {
prevNum = prevNum * den / g + num * prevDen / g
} else {
prevNum = prevNum * den / g - num * prevDen / g
}
prevDen = prevDen * den / g
val gcdValue = gcd(Math.abs(prevNum), prevDen)
prevNum /= gcdValue
prevDen /= gcdValue
i++
}
return "$prevNum/$prevDen"
}
private fun gcd(a: Int, b: Int): Int {
return if (b == 0) a else gcd(b, a % b)
}
}
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]
class Node(var `val`: Int) {
var children: List= listOf()
}
class Solution {
fun postorder(root: Node?): List{
if (root == null) return listOf()
val stack = ArrayDeque()
val output = mutableListOf()
stack.add(root)
while (stack.isNotEmpty()) {
val node = stack.removeLast()
output.add(node.`val`)
for (child in node.children) {
stack.add(child)
}
}
return output.reversed()
}
}
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
class Solution {
fun reverseWords(s: String): String {
val chars = s.toCharArray()
var lastSpaceIndex = -1
val len = chars.size
for (strIndex in 0..len) {
if (strIndex == len || chars[strIndex] == ' ') {
var startIndex = lastSpaceIndex + 1
var endIndex = strIndex - 1
while (startIndex < endIndex) {
val temp = chars[startIndex]
chars[startIndex] = chars[endIndex]
chars[endIndex] = temp
startIndex++
endIndex--
}
lastSpaceIndex = strIndex
}
}
return String(chars)
}
}
Input: n = 12
Output: 21
class Solution {
private fun swap(s: String, i0: Int, i1: Int): String {
if (i0 == i1) return s
val chars = s.toCharArray()
val temp = chars[i0]
chars[i0] = chars[i1]
chars[i1] = temp
return String(chars)
}
private val list = mutableListOf()
private fun permute(a: String, l: Int, r: Int) {
if (l == r) {
list.add(a)
} else {
var a = a
for (i in l..r) {
a = swap(a, l, i)
permute(a, l + 1, r)
a = swap(a, l, i)
}
}
}
fun nextGreaterElement(n: Int): Int {
val s = n.toString()
permute(s, 0, s.length - 1)
list.sort()
val index = list.indexOf(s)
if (index != -1 && index < list.size - 1) {
val result = list[index + 1].toInt()
if (result <= Int.MAX_VALUE) return result
}
return -1
}
}
Input: wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]
Output: 2
class Solution {
fun leastBricks(wall: List>): Int {
val pos = IntArray(wall.size)
var res = Int.MAX_VALUE
var sum = wall[0].sum()
while (sum != 0) {
var count = 0
for (i in wall.indices) {
if (wall[i][pos[i]] != 0) {
count++
} else {
pos[i]++
}
wall[i][pos[i]]--
}
sum--
res = Math.min(res, count)
}
return res
}
}
Input: password = "a"
Output: 5
fun strongPasswordChecker(s: String): Int {
val n = s.length
var hasLower = false
var hasUpper = false
var hasDigit = false
var repeatCount = 0
var i = 0
while (i < n) {
if (s[i].isLowerCase()) hasLower = true
if (s[i].isUpperCase()) hasUpper = true
if (s[i].isDigit()) hasDigit = true
val start = i
while (i < n && s[i] == s[start]) {
i++
}
repeatCount += (i - start) / 3
}
val missingTypes = (if (hasLower) 0 else 1) + (if (hasUpper) 0 else 1) + (if (hasDigit) 0 else 1)
return when {
n < 6 -> maxOf(missingTypes, 6 - n)
n <= 20 -> maxOf(missingTypes, repeatCount)
else -> {
val excessChars = n - 20
var overLenReduction = 0
i = 2
while (i < n && excessChars > 0) {
if (i % 3 == 2 && s[i] == s[i - 1] && s[i] == s[i - 2]) {
overLenReduction++
excessChars--
}
i++
}
repeatCount -= overLenReduction
(n - 20) + maxOf(missingTypes, repeatCount)
}
}
}
Input: nums = [1000,100,10,2]
Output: "1000/(100/10/2)"
Explanation: 1000/(100/10/2) = 1000/((100/10)/2) = 200
However, the bold parenthesis in "1000/((100/10)/2)" are redundant since they do not influence the operation priority.
So you should return "1000/(100/10/2)".
Other cases:
1000/(100/10)/2 = 50
1000/(100/(10/2)) = 50
1000/100/10/2 = 0.5
1000/100/(10/2) = 2
class Solution {
private fun addStrings(num1: List, num2: List ): List {
val ans = mutableListOf()
var carry = 0
val n1 = num1.size
val n2 = num2.size
for (i in 0 until maxOf(n1, n2) + 1) {
val digit1 = if (i < n1) num1[i] else 0
val digit2 = if (i < n2) num2[i] else 0
val sum = digit1 + digit2 + carry
carry = sum / 10
ans.add(sum % 10)
}
return ans
}
private fun multiplyOneDigit(firstNumber: String, secondNumberDigit: Char, numZeros: Int): List{
val currentResult = MutableList(numZeros) { 0 }
var carry = 0
for (digit in firstNumber) {
val multiplication = (secondNumberDigit.digitToInt() * digit.digitToInt()) + carry
carry = multiplication / 10
currentResult.add(multiplication % 10)
}
if (carry != 0) {
currentResult.add(carry)
}
return currentResult
}
fun multiply(firstNumber: String, secondNumber: String): String {
if (firstNumber == "0" || secondNumber == "0") {
return "0"
}
val firstNumber = firstNumber.reversed()
val secondNumber = secondNumber.reversed()
var ans = MutableList(firstNumber.length + secondNumber.length) { 0 }
for ((i, digit) in secondNumber.withIndex()) {
ans = addStrings(multiplyOneDigit(firstNumber, digit, i), ans)
}
while (ans.last() == 0) {
ans.removeAt(ans.size - 1)
}
return ans.reversed().joinToString("")
}
}
Input: board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]
Output: 2
fun countBattleships(board: Array): Int {
val m = board.size
val n = board[0].size
var count = 0
for (i in 0 until m) {
for (j in 0 until n) {
if (board[i][j] == 'X') {
if ((i == 0 || board[i-1][j] != 'X') && (j == 0 || board[i][j-1] != 'X')) {
count++
}
}
}
}
return count
}
Input: sentence = ["hello","world"], rows = 2, cols = 8
Output: 1
fun wordsTyping(sentence: Array, rows: Int, cols: Int): Int {
val sentenceStr = sentence.joinToString(" ") + " "
val length = sentenceStr.length
var pos = 0
for (i in 0 until rows) {
pos += cols
if (sentenceStr[pos % length] == ' ') {
pos++
} else {
while (pos > 0 && sentenceStr[(pos - 1) % length] != ' ') {
pos--
}
}
}
return pos / length
}
Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
fun pacificAtlantic(heights: Array): List > {
val m = heights.size
val n = heights[0].size
val pacific = Array(m) { BooleanArray(n) }
val atlantic = Array(m) { BooleanArray(n) }
val directions = arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(0, 1))
fun dfs(r: Int, c: Int, ocean: Array) {
ocean[r][c] = true
for (dir in directions) {
val nr = r + dir[0]
val nc = c + dir[1]
if (nr in 0 until m && nc in 0 until n && !ocean[nr][nc] && heights[nr][nc] >= heights[r][c]) {
dfs(nr, nc, ocean)
}
}
}
for (i in 0 until m) {
dfs(i, 0, pacific)
dfs(i, n - 1, atlantic)
}
for (j in 0 until n) {
dfs(0, j, pacific)
dfs(m - 1, j, atlantic)
}
val result = mutableListOf>()
for (i in 0 until m) {
for (j in 0 until n) {
if (pacific[i][j] && atlantic[i][j]) {
result.add(listOf(i, j))
}
}
}
return result
}
Input: nums = [1,5,11,5]
Output: true
fun canPartition(nums: IntArray): Boolean {
val sum = nums.sum()
if (sum % 2 != 0) return false
val target = sum / 2
val dp = BooleanArray(target + 1) { false }
dp[0] = true
for (num in nums) {
for (j in target downTo num) {
dp[j] = dp[j] || dp[j - num]
}
}
return dp[target]
}
Input: num1 = "11", num2 = "123"
Output: "134"
fun thirdMax(nums: IntArray): Int {
var first: Int? = null
var second: Int? = null
var third: Int? = null
for (num in nums) {
if (num == first || num == second || num == third) {
continue
}
when {
first == null || num > first -> {
third = second
second = first
first = num
}
second == null || num > second -> {
third = second
second = num
}
third == null || num > third -> {
third = num
}
}
}
return third ?: first!!
}