Created
April 15, 2024 02:22
-
-
Save AriTedeschi/fc4559568e2552da3164180287febe5f to your computer and use it in GitHub Desktop.
TwoSum Solution
This file contains 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
import java.util.List; | |
import java.util.Arrays; | |
import java.util.ArrayList; | |
public class Main | |
{ | |
//O(n) | |
public static String twoSum(List numbers, int target){ | |
Integer head = 0, | |
tail = numbers.size()-1, | |
sum = 0; | |
while(head < tail){ | |
sum = (int) numbers.get(head) + (int) numbers.get(tail); | |
if(sum == target) | |
return String.format("%s# element + %s# element = %s + %s = %s", | |
head+1, | |
tail+1, | |
(int) numbers.get(head), | |
(int) numbers.get(tail), | |
target); | |
if(sum > target) | |
tail-=1; | |
else | |
head+=1; | |
} | |
return null; | |
} | |
public static void main(String[] args) { | |
Integer[] a = new Integer[] {1,1,1,2,2,3,4,5,5,6,7,9,9}; | |
List<Integer> numbers = Arrays.asList(a); | |
System.out.println(twoSum(numbers,9)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment