Skip to content

Instantly share code, notes, and snippets.

@woodRock
Last active December 9, 2023 21:11
Show Gist options
  • Save woodRock/e71430ea29860a90bc83f9beb7f83ca4 to your computer and use it in GitHub Desktop.
Save woodRock/e71430ea29860a90bc83f9beb7f83ca4 to your computer and use it in GitHub Desktop.
Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. Bonus: Can you do this in one pass?
import java.util.ArrayList;
import java.util.Arrays;
class ListAddition {
public static boolean list_add(int k, int[] list){
for (int i=0; i<list.length; i++){
for (int j=i+1; j<list.length; j++){
if (list[i]+list[j]==k)
return true;
}
}
return false;
}
public static void main(String [] args){
int[] l = {10,15,3,7};
System.out.println(list_add(17, l));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment