Tuesday, 12 September 2017

Two Sum on arrays


Given an array of integers, return indices of the two numbers such that they add up to a specific target.
Example:
Given nums = [ 3, 4, 5, 2, 10, 8, 9 ]
target = 19
Because nums[4] + nums[6] = 10 + 9 = 19, return [4, 6]
Approach:
step1. take 3 and then add 3 with all other elements
step2. take 4 and then add 4 with all other elements.Continue same till 9

 
      TwoSum.java  
public class TwoSum { public static void main(String[] args) { int[] arr = { 3, 4, 5, 2, 10, 8, 9 }; int target = 19; TwoSum app = new TwoSum(); int[] rslt = app.twosum(arr, target); System.out.print(rslt[0] + ", " + rslt[1]); } private int[] twosum(int[] arr, int target) { int[] rslt = new int[2]; // take 3 and then add 3 with all other // take 4 and then add 4 with all other elemnts.Continue same till 9 for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { if (j != i) { // don't add the same indexes int sum = arr[i] + arr[j]; if (sum == target) { rslt[0] = i; rslt[1] = j; break; } } } } return rslt; } } /* ****** INPUT ******** { 3, 4, 5, 2, 10, 8, 9 } 19 ******* INPUT ******** ****** OUTPUT ******** 4, 6 ******* OUTPUT ******** */

No comments:

Post a Comment

Search This Blog

Contact us

Name

Email *

Message *