Write a program to Find indices of the two numbers such that they add up to the target in the given array
ExampleInput: [1,0,5,3,6,8], targer=9
Output: [0,4] or [1,5]
ApproachJava
import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import javafx.util.Pair;public class TwoSum {public static void main(String aa[]) {TwoSum s = new TwoSum();int[] nums = { 1, 0, 5, 3, 8, 9 };int target = 9;int result[] = s.twoSum(nums, target);System.out.println(Arrays.toString(result));// [1,5]}public int[] twoSum(int[] nums, int target) {ArrayList<Pair<Integer, Integer>> l =new ArrayList<Pair<Integer, Integer>>();for (int i = 0; i < nums.length; i++) {Pair p = new Pair(nums[i], i);l.add(p);}// sort Pair of array list based on keyCollections.sort(l, new Comparator<Pair<Integer, Integer>>() {@Overridepublic int compare(final Pair<Integer, Integer> o1,final Pair<Integer, Integer> o2) {return o1.getKey() - o2.getKey();}});int sP = 0, lP = nums.length - 1;while (sP < lP) {if ((l.get(sP).getKey() + l.get(lP).getKey()) == target) {return new int[] { l.get(sP).getValue(), l.get(lP).getValue() };} else if ((l.get(sP).getKey() + l.get(lP).getKey()) > target) {lP--;} else {sP++;}}return null;}}
No comments:
Post a Comment