diff --git a/contest/src/main/java/com/github/contest/array/ArrayLeetcode.kt b/contest/src/main/java/com/github/contest/array/ArrayLeetcode.kt index ff335c50..aaaf4573 100644 --- a/contest/src/main/java/com/github/contest/array/ArrayLeetcode.kt +++ b/contest/src/main/java/com/github/contest/array/ArrayLeetcode.kt @@ -178,7 +178,34 @@ fun maximumTripletValue(nums: IntArray): Long { return res } +/** + * 189. Rotate Array + */ + +fun rotate(nums: IntArray, k: Int) { + if (k % nums.size != 0) { + val cache = mutableListOf() + val bound = when { + k > nums.size -> { + val temp = k % nums.size + nums.size - temp + } + + else -> nums.size - k + } + for (i in bound until nums.size) { + cache.add(nums[i]) + } + + for (i in 0 until bound) { + cache.add(nums[i]) + } + for (i in 0 until cache.size) { + nums[i] = cache[i] + } + } +} diff --git a/contest/src/main/java/com/github/contest/dp/DpLeetcode.kt b/contest/src/main/java/com/github/contest/dp/DpLeetcode.kt index 3edd750e..cb633014 100644 --- a/contest/src/main/java/com/github/contest/dp/DpLeetcode.kt +++ b/contest/src/main/java/com/github/contest/dp/DpLeetcode.kt @@ -597,6 +597,31 @@ fun canJump(nums: IntArray): Boolean { return true } +/** + * 45. Jump Game II + */ + +fun jump(nums: IntArray): Int { + var jumps = 0 + var currentEnd = 0 + var farthest = 0 + + for (i in 0 until nums.size - 1) { + farthest = maxOf(farthest, i + nums[i]) + + if (i == currentEnd) { + jumps++ + currentEnd = farthest + + if (currentEnd >= nums.size - 1) { + break + } + } + } + + return jumps +} +