Created
October 13, 2020 15:22
-
-
Save javabuddy/4694243da1934a68e421dc8002b7a128 to your computer and use it in GitHub Desktop.
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 org.junit.Assert; | |
/** | |
* My solution of classical two sum problem in Java. | |
Problem - Given an array of | |
* integers, find two numbers such that they add up to | |
a specific target number. | |
* | |
* The method twoSum should return indices of the two numbers such that they add | |
* up to the target, where index1 must be less than index2. | |
Please note that | |
* your returned answers (both index1 and index2) are not zero-based. | |
* | |
* Note: You may assume that each input would have exactly one solution. | |
* | |
* Example [2,7,11,15], 9 -> [1,2] | |
* | |
* @author Javin Paul | |
* | |
*/ | |
public class TwoSum { | |
public static int[] twoSum(int[] input, int target) { | |
for (int i = 0; i < input.length; i++) { | |
int first = input[i]; | |
for (int j = i + 1; j < input.length; j++) { | |
int second = input[j]; | |
int total = first + second; | |
if (total == target) { | |
return new int[] { i + 1, j + 1 }; | |
} | |
} | |
} | |
return null; | |
} | |
public static void main(String args[]) { | |
// return pairs which adds to 29 in given array | |
Assert.assertArrayEquals(new int[] { 1, 2 }, | |
twoSum(new int[] { 12, 17, 21, 25 }, 29)); | |
} | |
} |
And if you need more coding problme - check these 50+ data structures and algorithms questions
More data structure articles you may like to check
https://medium.com/free-code-camp/these-are-the-best-free-courses-to-learn-data-structures-and-algorithms-in-depth-4d52f0d6b35a
https://medium.com/javarevisited/7-best-courses-to-learn-data-structure-and-algorithms-d5379ae2588?source=---------18------------------
https://javarevisited.blogspot.com/2015/07/5-data-structure-and-algorithm-books-best-must-read.html
https://www.java67.com/2018/06/data-structure-and-algorithm-interview-questions-programmers.html
https://medium.com/javarevisited/top-21-string-programming-interview-questions-for-beginners-and-experienced-developers-56037048de45
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Full solution - https://www.java67.com/2020/07/how-to-solve-two-sum-array-problem-in-java.html