29 Jul 2017
LeetCode – Two Sum
LeetCode – Two Sum- Given an array of integers, find two numbers such that they add up to a specific target number.
This problem i.e. Two Sum is one of the most frequently asked programming question in most interviews especially for a junior level programmer.
Analysis: This problem is pretty straightforward. We can simply examine every possible pair of numbers in this integer array. When the first number is greater than the target, there is no need to find the second number & when the sum of the two numbers match the target we simply break and return the pair of number.
Java Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.heapcode.leetcode; public class TwoSum { public static void main(String []args){ int input [] = {3,2,4}; int target = 6; int [] result = twoSum(input,target); System.out.println("Result: "+result[0]+","+result[1]); } public static int[] twoSum(int[] numbers, int target){ int []ret = new int[2]; for(int i=0; i<numbers.length;i++){ if(numbers[i] <= target){ for(int j=i+1;j<numbers.length;j++) { if(numbers[i] + numbers[j] == target) { ret[0]= numbers[i]; ret[1]= numbers[j]; } } } } return ret ; } } |
I hope this has been useful for you and I’d like to thank you for reading. If you like this article, please leave a helpful comment and share it with your friends.