Monday, February 20, 2017

[Java][Answer] CodingBat Array-2 > has22

Given an array of ints, return true if the array contains a 2 next to a 2 somewhere.

has22([1, 2, 2]) → true
has22([1, 2, 1, 2]) → false
has22([2, 1, 2]) → false

Answer 1:

public boolean has22(int[] nums) {
  for(int i=0;i<nums.length;i++){
    if(i-1>=0){
      if(nums[i]==2 && nums[i-1]==2) return true;
    }
  }
  return false;
}

Answer 2:

public boolean has22(int[] nums) {
  boolean found = false;
 
  for (int i = 0; i < nums.length; i++) {
    if (nums[i] == 2 && i > 0 && nums[i-1] == 2) {
      found = true;
    }
    if (nums[i] == 2 && i < nums.length-1 && nums[i+1] == 2) {
      found = true;
    }
  }
  return found;
}

Reference

http://www.javaproblems.com/2013/11/java-array-2-has22-codingbat-solution.html

No comments :

Post a Comment