Deepeshkumar - 2 months ago 31

Java Question

I came across this problem on codingbat.com : Problem

Problem:

Given an array of ints, return true if the array contains two 7's next to each other, or there are two 7's separated by one element, such as with {7, 1, 7}.

has77([1, 7, 7]) → true

has77([1, 7, 1, 7]) → true

has77([1, 7, 1, 1, 7]) → false

I solved it but my approach is not that efficient. The code of my solution is large compared to the problem. Can anybody show me how to solve this problem in a smart way.

My code:

`public boolean has77(int[] nums) {`

int i = 0;

int arraylength = 0;

while(i != nums.length){

if(nums[i] == 7){

arraylength++;

}

i++;

}

int[] sevens = new int[arraylength];

if(arraylength == 0){

return false;

}

i =0;

int j = 0;

while(i != nums.length){

if(nums[i] == 7){

sevens[j] = i;

j++;

}

i++;

}

i = 0;

while(i != arraylength-1){

if(sevens[i+1] - sevens[i]==1 || (sevens[i+1]- sevens[i]==2)){

return true;

}

i++;

}

return false;

}

Answer

This answer will tell you *how* to do it, but will not give you the code. Writing the code is for you to do, since you chose at accept the challenge on CodingBat.

*More efficiently solution:* Only iterate the array once. If current element is a 7, and previous element or the one before it is also a 7, return `true`

.