Wednesday, February 10, 2016

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

Given an array of ints, return true if there is a 1 in the array with a 2 somewhere later in the array.

has12([1, 3, 2]) → true
has12([3, 1, 2]) → true
has12([3, 1, 4, 5, 2]) → true

Answer 1:
public boolean has12(int[] nums) {
  boolean has1 = false;
  for(int i =0;i<nums.length;i++){
    if(nums[i]==1) has1 = true;
    if(has1 && nums[i]==2) return true;
  }
  return false;
}
Answer 2:
public boolean has12(int[] nums) {
  boolean foundOne = false;
  boolean foundOneTwo = false;
 
  for (int i = 0; i < nums.length; i++) {
    if (nums[i] == 1)
      foundOne = true;
    if (nums[i] == 2 && foundOne)
      foundOneTwo = true;
  }
  return foundOneTwo;
}
Reference
http://www.javaproblems.com/2013/11/java-array-2-has12-codingbat-solution.html

No comments :

Post a Comment