Created
August 30, 2019 17:09
-
-
Save indranil32/a2f3e028e399e4734161cf2a7255e733 to your computer and use it in GitHub Desktop.
o(n) implementation of two sum for sorted array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def arr2 = [1,3,4,5,9] | |
def sum = 16 | |
def twoSum(arr, sum) { | |
if (arr[0] > sum) return; | |
if (arr[1] > sum || arr[1] + arr[0] > sum) return; | |
int i = 0; | |
int j = arr.size() -1 | |
for ( ; i < j ; ) { | |
if ((arr[i] + arr[j]) > sum) { | |
j--; | |
} else if ((arr[i] + arr[j]) < sum){ | |
i++; | |
} else { | |
println "found" | |
return; | |
} | |
} | |
} | |
twoSum(arr2, sum) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment