TwoSum

TwoSum

This sample code show how to achieve two distinct zero-based indices of any two of the numbers, whose sum is equal to the target sum. 

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TwoSum {
	
  public static boolean checkDuplicate(List<Integer[]> values, Integer[] obj) {
    boolean duplicate = false;
    StringBuffer item = new StringBuffer(toString(obj));
		
    for ( Integer[] value: values) {
      String compare = toString(value);
      if (item.toString().equals(compare) || item.reverse().toString().equals((compare))) {
        duplicate = true;
        break;
      }
    }
    return duplicate;
  }

  public static String toString(Integer[] array) {
    StringBuffer sb = new StringBuffer();
    for (int i=0; i < array.length; i++) {
        sb.append(array[i]);
    }
    return sb.toString();
  }	

  public static int[] findTwoSum(int[] numbers, int sum) {

    List<Integer[]> index = new ArrayList<>();
    List<Integer[]> value = new ArrayList<>();

    for (int i=0; i < numbers.length; i++) {
      for (int j=i+1; j < numbers.length; j++) {
        // when sum = 2 digit total up
        if ( sum == numbers[i] + numbers[j]) {
          if (!checkDuplicate(value, new Integer[] { numbers[i], numbers[j] })) {
               index.add(new Integer[] {i, j});
               value.add(new Integer[] {numbers[i], numbers[j]});
          }
        }
      }
    }
    int size = index.size();
    if ( size > 0 ) {
      int[] result = Arrays.stream(index.get(size-1)).mapToInt(Integer::intValue).toArray(); //unboxed
      return result;
    }
    return null;
  }

  public static void main(String[] args) {
     int[] indices = findTwoSum(new int[] { 3, 1, 5, 7, 5, 9 }, 10);
     if (indices != null) {
	System.out.println(indices[0] + " " + indices[1]);
     }
  }
} 

Write a Reply or Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.