Skip to content

Instantly share code, notes, and snippets.

@AriTedeschi
Created April 15, 2024 02:22
Show Gist options
  • Save AriTedeschi/fc4559568e2552da3164180287febe5f to your computer and use it in GitHub Desktop.
Save AriTedeschi/fc4559568e2552da3164180287febe5f to your computer and use it in GitHub Desktop.
TwoSum Solution
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