Find two numbers in the array

Given an array of integers num and an integer target, find two numbers in the array that add up to target and return their indices.

  • Input: num = [1, 4, 9, 12], target = 5
  • Output: [0, 1]
  • Explanation: Because num[0] + num[1] == 5, we return [0, 1].
package com.javainfotech.arrays;
import java.util.Arrays;
public class TwoSum {
	public static void main(String[] args) {
		//Create array
		int[] num = {1, 4, 9, 12};
		int target = 5;
		int[] result = getTwoSum(num,target);
		System.out.println("Result indices : "+Arrays.toString(result));
	}	
	//Method create to get the indices
	public static int[] getTwoSum(int[] num, int target) {
        int[] ans = new int[2];
        for(int i=0;i<num.length;i++) {
        	for(int j=i+1;j<num.length;j++) {        		
        		if(num[i]+num[j]==target) {
        			ans[0]=i;
        			ans[1]=j;
        			return ans;//Return indices
        		}
        	}        
        }
        return new int[] {-1,-1};
    }
}

Happy Learning!!!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *