Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions contains-duplicate/devdays9.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
class Solution {
fun containsDuplicate(nums: IntArray): Boolean {
val occurrences = HashSet<Int>(nums.size)
return nums.any { !occurrences.add(it) }
}
}
15 changes: 15 additions & 0 deletions house-robber/devdays9.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import kotlin.math.max

class Solution {
fun rob(nums: IntArray): Int {
var prevMaxMoney = 0
var maxMoney = 0
for (money in nums) {
prevMaxMoney.let {
prevMaxMoney = maxMoney
maxMoney = max(it + money, maxMoney)
}
}
return maxMoney
}
}
19 changes: 19 additions & 0 deletions longest-consecutive-sequence/devdays9.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import kotlin.math.max

class Solution {
fun longestConsecutive(nums: IntArray): Int {
val numsSet = nums.toHashSet()
var maxLength = 0
for (num in numsSet) {
if (num - 1 in numsSet) {
continue
}
var length = 1
while (num + length in numsSet) {
++length
}
maxLength = max(length, maxLength)
}
return maxLength
}
}
18 changes: 18 additions & 0 deletions top-k-frequent-elements/devdays9.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import java.util.PriorityQueue

typealias Number = Int
typealias Frequency = Int

class Solution {
fun topKFrequent(nums: IntArray, k: Int): IntArray {
val frequencyMap = HashMap<Number, Frequency>(nums.size)
nums.forEach {
frequencyMap.merge(it, 1, Int::plus)
}
val heap = PriorityQueue<Int>(frequencyMap.size) { num1, num2 ->
frequencyMap[num2]!!.compareTo(frequencyMap[num1]!!)
}
heap += frequencyMap.keys
return IntArray(k) { heap.poll() }
}
}
15 changes: 15 additions & 0 deletions two-sum/devdays9.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
typealias Number = Int
typealias Index = Int

class Solution {
fun twoSum(nums: IntArray, target: Int): IntArray {
val occurrences = HashMap<Number, Index>(nums.size)
nums.forEachIndexed { index, num ->
occurrences[target - num]?.let { complementIndex ->
return intArrayOf(index, complementIndex)
}
occurrences[num] = index
}
return intArrayOf()
}
}