Social Icons

Thursday, April 22, 2010

linearIn: Solutions for Javabat:12


Question:
Given two arrays of ints sorted in increasing order, outer and inner, return true if all of the numbers in inner appear in outer. The best solution makes only a single "linear" pass of both arrays, taking advantage of the fact that both arrays are already in sorted order.

linearIn({1, 2, 4, 6}, {2, 4}) → true
linearIn({1, 2, 4, 6}, {2, 3, 4}) → false
linearIn({1, 2, 4, 4, 6}, {2, 4}) → true

Source:

public boolean linearIn(int[] outer, int[] inner) {
  boolean b[]=new boolean[inner.length];
  boolean b1=true;
  
  for(int i=0;i<inner.length;i++){
     for(int j=0 ; j<outer.length;j++){
        if(inner[i]==outer[j])
           b[i]=true;
     }
  }
  for(boolean b2:b)
    b1 &= b2;
    
  return b1;  
}
 
 
 
 
Blogger Templates http://slots.to/