Sunday, May 13, 2018

Find two pair of index or two sum of index in a list

Problem statement: Given an array of integers, return indices of two numbers such that they add up to a specific target.
e.g. - arr[] = { 4, 6, 5, -10, 8, 5, 20 };
target = 10
Output: [4,6] , [5,5], [-10,20]

Note: You may assume that each input would have exactly one solution, and you may not use the same element twice.

  1. import java.util.HashMap;
  2. import java.util.Map;

  3. public class IndexOfTwoPair{

  4. public static void main(String[] args) {
  5. int a[] = { 4, 6, 5, -10, 8, 5, 20 };
  6. int n = 10;
  7. int idx[] = indexOfTwoSum(a, n);
  8. for (int i : idx) {
  9. System.out.print(i + " ");
  10. }
  11. }
  12. public static int[] indexOfTwoSum(int nums[], int target) {
  13. // array to return the result
  14. int arr[] = new int[2];

  15. // map for num and index pair
  16. Map<Integer, Integer> map = new HashMap<Integer, Integer>();

  17. // scan the array element
  18. for (int i = 0; i < nums.length; i++) {
  19. // check if map has an element which is equal to difference
  20. // between target and current element
  21. Integer val = map.get(target - nums[i]);
  22. if (val == null) {
  23. // no match found, add current element & index to map
  24. map.put(nums[i], i);
  25. } else {
  26. // match found, update the index values
  27. arr[0] = val;
  28. arr[1] = i;
  29. }
  30. }
  31. return arr;
  32. }
  33. }
Output:
3 6

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...