Friday, November 25, 2011

Pairs in array sum upto K

package arrays;

import java.util.HashMap;
import java.util.Map;


public class ArrayPairs {
public static void main(String[]args){
  int a[]={3,4,5,4,1,2};
  int sum=9;
  boolean found=false;
  Map<Integer,Integer> map = new HashMap<Integer,Integer>();

 
  for(int b : a){
    if(map.containsKey(b)){
      System.out.println("Pairs are :" + b + "," + map.get(b));
      found = true;
    }
    else {
      int diff=sum-b;
      map.put(diff, b);
    }
  }
  if(!found)
    System.out.println("No such pairs are there");
}
}

No comments:

Post a Comment