Two Sums Program (Leetcode)

Two Sums Program (Leetcode):


import java.util.*;
import java.io.*;
class Two_Sum
{
       public static void main(String args[])
       {
              Scanner sc = new Scanner(System.in);
              ArrayList<Integer> nums = new ArrayList<Integer>();
              System.out.println("How many numbers you want to Enter");
              int n = sc.nextInt();
              System.out.println("Enter Numbers");
              for(int x = 0;x <= n-1 ; x++)
              {
                     nums.add(sc.nextInt());
              }
              System.out.println("Enter Target");
              int target = sc.nextInt();
              ArrayList<Integer> l = new ArrayList<Integer>();
              for(int i:nuns)
              {
                     int index = nums.indexOf(i);
                     l.add(index);
                     if(nums.contains(target - I))
                     {
                            /* nums = [3,2,4] */
                            /* first element is 3 target is 6 therefore 
                                we must check that the index don't repeat */
                            if(index != nums.indexOf(target - I))
                            {
                                   l.add(nums.indexOf(target - I));
                            }
                            else
                            {
                                   Collections.reverse(nums);
                                   l.add(nums.size() - 1 -
                                                  nums.indexOf(target - I));
                            }

                            /* nums = [3,3] */
                            if(l.get(0) == l.get(1))
                            {
                                   Collections.reverse(nums);
                                   l = new ArrayList<Integer>();
                                   continue;
                            }
                            break;
                     }
                     else
                            l = new ArrayList<Integer>();
              }
              System.out.println(l);
       }
}

Input:

nums = [1,2,3,4]
target = 6

nums = [3,2,4]
target = 6

nums = [3,3]
target = 6

Output:
l = [1,3]
l = [1,2]
l = [1,1]

Here [1,3] are index of [2,4] because the sum of [2,4] equals to 6.

Explanation:

This program can be done with the help of HashMap but here I have done with the help of ArrayList.
Ex: nums = [1,2,3,4]       target = 6
then
we add index of first element in the ArrayList and check if  the (target - num[index]) present in nums.

Post a Comment

0 Comments