Skip to content

Instantly share code, notes, and snippets.

@rpandey1234
Last active September 23, 2020 08:27
Show Gist options
  • Save rpandey1234/2f5664a415ae48604aa74a80831bfd7f to your computer and use it in GitHub Desktop.
Save rpandey1234/2f5664a415ae48604aa74a80831bfd7f to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/two-sum/submissions/
fun twoSum(nums: IntArray, target: Int): IntArray {
for (index1 in nums.indices) {
val startIndex = index1 + 1
for (index2 in startIndex..nums.lastIndex) {
if (nums[index1] + nums[index2] == target) {
return intArrayOf(index1, index2)
}
}
}
return intArrayOf(0, 1)
}
// https://leetcode.com/problems/container-with-most-water/submissions/
fun maxArea(heights: IntArray): Int {
var maxArea = 0
for (index1 in heights.indices) {
val startIndex = index1 + 1
for (index2 in startIndex..heights.lastIndex) {
val tankHeight = Math.min(heights[index1], heights[index2])
val tankWidth = index2 - index1
maxArea = Math.max(tankHeight * tankWidth, maxArea)
}
}
return maxArea
}
// https://leetcode.com/problems/count-and-say/submissions/
fun countAndSay(n: Int): String {
if (n == 1) {
return "1"
}
var answerTillHere = countAndSay(n - 1)
var currentPosition = 0
var newString = ""
while (currentPosition < answerTillHere.length) {
val cnt = countInstancesOfChar(currentPosition, answerTillHere)
newString += cnt.toString() + answerTillHere[currentPosition]
currentPosition += cnt
}
return newString
}
fun countInstancesOfChar(startIndex: Int, s: String): Int {
var count = 0
for (index in startIndex .. s.lastIndex) {
if (s[index] == s[startIndex]) {
count++
} else {
return count
}
}
return count
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment