Monday, April 20, 2015

[Java][Answer] CodingBat Array-2 > haveThree()

Given an array of ints, return true if the value 3 appears in the array exactly 3 times, and no 3's are next to each other.

haveThree([3, 1, 3, 1, 3]) → true
haveThree([3, 1, 3, 3]) → false
haveThree([3, 4, 3, 3, 4]) → false

Answer 1:
public boolean haveThree(int[] nums) {
  int count3 = 0;
  for(int i=0;i<nums.length;i++){
    if(nums[i]==3){
      count3++;
      if(i<nums.length-1 && nums[i+1]==3)return false;
    }
  }
  return count3==3;
}
Answer 2:
public boolean haveThree(int[] nums) {
  int count = 0;
  boolean found = false;
 
  for (int i = 0; i < nums.length; i++) {
    if (nums[i] != 3)
      found = false;
    if (nums[i] == 3 && found == true)
      return false;
    if (nums[i] == 3 && found == false) {
      found = true;
      count++;
    }
  }
  if (count == 3)
    return true;
  else
   return false;
}
Reference
http://www.javaproblems.com/2013/11/java-array-2-havethree-codingbat.html

No comments :

Post a Comment