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;  
}
 
 

Comments (2)

Loading... Logging you in...
  • Logged in as
fish chuchu's avatar

fish chuchu · 616 weeks ago

what if I do it this way
public boolean canBalance(int[] nums) {
int totalSum = 0;
int parSum=0;

for (int i=0;i<nums.length;i++)
{
totalSum = totalSum+nums[i];
}
for(int j=0;j<nums.length;j++)
{
parSum=parSum+nums[j];
if(parSum==totalSum-parSum)
{
return true;
}
}
return false;
}
fish chuchu's avatar

fish chuchu · 616 weeks ago

sorry this way the above is for another question

public boolean linearIn(int[] outer, int[] inner) {
int count =0;
for (int i=0;i<inner.length;i++)
{
for (int j=0;j<outer.length;j++)
{
if(inner [i]==outer[j])
{
count++;
break;

}
}

}
if (count==inner.length)
{
return true;
}
return false;
}

Post a new comment

Comments by

 
 
Blogger Templates http://slots.to/