diff --git a/contains-duplicate/devdays9.kt b/contains-duplicate/devdays9.kt new file mode 100644 index 000000000..8facf3333 --- /dev/null +++ b/contains-duplicate/devdays9.kt @@ -0,0 +1,6 @@ +class Solution { + fun containsDuplicate(nums: IntArray): Boolean { + val occurrences = HashSet(nums.size) + return nums.any { !occurrences.add(it) } + } +} diff --git a/house-robber/devdays9.kt b/house-robber/devdays9.kt new file mode 100644 index 000000000..5b720a7eb --- /dev/null +++ b/house-robber/devdays9.kt @@ -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 + } +} diff --git a/longest-consecutive-sequence/devdays9.kt b/longest-consecutive-sequence/devdays9.kt new file mode 100644 index 000000000..e0a1b4f29 --- /dev/null +++ b/longest-consecutive-sequence/devdays9.kt @@ -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 + } +} diff --git a/top-k-frequent-elements/devdays9.kt b/top-k-frequent-elements/devdays9.kt new file mode 100644 index 000000000..032f5d98a --- /dev/null +++ b/top-k-frequent-elements/devdays9.kt @@ -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(nums.size) + nums.forEach { + frequencyMap.merge(it, 1, Int::plus) + } + val heap = PriorityQueue(frequencyMap.size) { num1, num2 -> + frequencyMap[num2]!!.compareTo(frequencyMap[num1]!!) + } + heap += frequencyMap.keys + return IntArray(k) { heap.poll() } + } +} diff --git a/two-sum/devdays9.kt b/two-sum/devdays9.kt new file mode 100644 index 000000000..3cb3eab7e --- /dev/null +++ b/two-sum/devdays9.kt @@ -0,0 +1,15 @@ +typealias Number = Int +typealias Index = Int + +class Solution { + fun twoSum(nums: IntArray, target: Int): IntArray { + val occurrences = HashMap(nums.size) + nums.forEachIndexed { index, num -> + occurrences[target - num]?.let { complementIndex -> + return intArrayOf(index, complementIndex) + } + occurrences[num] = index + } + return intArrayOf() + } +}