Social Icons

Monday, April 12, 2010

sameEnds: Solutions for Javabat:07


This time i choose an array question. quite an easy one.

Return true if the group of N numbers at the start and end of the array are the same. For example, with {5, 6, 45, 99, 13, 5, 6}, the ends are the same for n=0 and n=2, and false for n=1 and n=3. You may assume that n is in the range 0..nums.length inclusive.

sameEnds({5, 6, 45, 99, 13, 5, 6}, 1) → false
sameEnds({5, 6, 45, 99, 13, 5, 6}, 2) → true
sameEnds({5, 6, 45, 99, 13, 5, 6}, 3) → false

Source

A loop should be used , in each pass we must compare two elements of the array which must be equal , Trick is to figure out the relation between the indices of two elements.

  1: public boolean sameEnds(int[] nums, int n) {
  2: 
  3:   boolean b=true;
  4:   if(n==0) return b; 
  5:   if(n>nums.length) return false;
  6:   
  7:   for(int i=0 ; i<n ; i++){
  8:      if( nums[i] != nums[nums.length-n+i] ) 
  9:         b=false;
 10:   }
 11:   
 12:   return b;
 13: }
 

 
 
Blogger Templates http://slots.to/