Java > Array-2 > has12 (CodingBat Solution)

Problem:

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


Solution:

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;
}


5 comments :

  1. boolean hasT = false;

    for(int i=0; i<nums.length-1; i++){
    if(nums[i] == 1){
    for(int j = i+1; j<nums.length; j++){
    if(nums[j] == 2) return true;
    }
    }
    }

    return false;

    ReplyDelete
  2. public boolean has12(int[] nums) {

    int i=0;
    int onePos = -1;
    int twoPos=-1;

    for(i=0;ionePos && onePos>=0){
    return true;
    }
    return false;
    }

    ReplyDelete
  3. public boolean has12(int[] nums) {
    boolean result = false;
    boolean found1 = false;
    boolean found2 = false;
    int search1 = 0;
    int search2 = 0;

    for(int i=0; i<nums.length; i++){
    if(nums[i] == 1){
    found1 = true;
    search1 = i;
    }
    }
    for(int j=0; j<nums.length; j++){
    if(nums[j] == 2){
    found2 = true;
    search2 = j;
    }
    }
    if(search1<search2 && found1 && found2)
    result = true;
    return result;
    }

    ReplyDelete
  4. public boolean has12(int[] nums) {

    for(int i=0; i<nums.length; i++){
    if(nums[i]==1){
    int[] arr= Arrays.copyOfRange(nums,i+1,nums.length);
    for(int j=0; j<arr.length; j++){
    if(arr[j]==2)
    return true;
    }
    }
    }
    return false;
    }

    ReplyDelete
  5. public boolean has12(int[] nums) {
    boolean flag = false;
    for(int i=0;i<nums.length;i++){
    if(nums[i]==1){
    flag = true;
    }
    if(flag && nums[i]==2){
    return true;
    }
    }
    return false;
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact