Wednesday, January 20, 2016

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

Given an array of ints, return true if every 2 that appears in the array is next to another 2.

twoTwo([4, 2, 2, 3]) → true
twoTwo([2, 2, 4]) → true
twoTwo([2, 2, 4, 2]) → false

Answer 1:
public boolean twoTwo(int[] nums) {
  for (int i = 0; i < nums.length; i++) {
    if (nums[i] == 2) {
      if (!(i < nums.length-1 && nums[i+1] == 2 ||
            nums.length > 1 && i > 0 && nums[i-1] == 2))
        return false;
    } 
  }
  return true;
}
Answer 2:
public boolean twoTwo(int[] nums) {
  boolean isTrue = false;
 
  for (int i = 0; i < nums.length; i++) {
    if (nums[i] == 2) {
      if (nums.length > 1 && i < nums.length-1 && nums[i+1] == 2)
        isTrue = true;
      else if (nums.length > 1 && i > 0 && nums[i-1] == 2)
        isTrue = true;
      else
        return false;
    } 
  }
  return true;
}
Reference
http://www.javaproblems.com/2013/11/java-array-2-twotwo-codingbat-solution.html

No comments :

Post a Comment