Skip to content

Add kotlin language for twoNumberSum #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
26 changes: 26 additions & 0 deletions Easy/Kotlin/twoNumberSum.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
@file:JvmName("Main")
fun main()
{
println("result is ${twoNumberSum(intArrayOf(1,-1,5,-2),3).contentToString()}")
}

// O(N) time and space
fun twoNumberSum(array:IntArray,targetSum:Int):IntArray {
if(array.size<2) return intArrayOf()
val set = mutableSetOf<Int>()
for(element in array)
{
if(set.contains(targetSum - element))
return intArrayOf(element,targetSum - element)
else
set.add(element)
}

return intArrayOf()
}

/* O(N^2) time, O(1) space
run two for loops and compare every pair to see if it matches.

O(N logN) time and O(1) space
sort the array first and then use the two pointer approach to find the target sum. */