Sunday, January 16, 2011

JAVA BAT : Array 1 : SameFirstLast

In Array 1 section, these are simple Array based problems in which there is no use of loops to solve the problems.

Same First Last Problem :Given an array of ints, return true if the array is length 1 or more, and the first element and the last element are the same.

sameFirstLast({1, 2, 3}) → false
sameFirstLast({1, 2, 3, 1}) → true
sameFirstLast({1, 2, 1}) → true

To solve this problem first we check weather the array given is of length greater then zero or not. To check this we use the method Array.length (For strings the method is String.length() ). Then we will check for the first and last element, are they same.

So the code for this problem: 


           public boolean sameFirstLast ( int[] nums ) {
 
                   if ( nums.length>0 ){
                             if ( nums[0]==nums[nums.length-1] ){
                                         return true;
                             }else{
                                       
return false;
                            }
                   }
                   else{
                            return false;
                   }

          }

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. why this doesnt work?


    if (nums[nums.length]>0 && nums[0]==nums[nums.length-1]){
    return true;
    }
    else {
    return false;
    }

    ReplyDelete