Problem:
Given an array of scores sorted in increasing order, return true if the array contains 3 adjacent scores that differ from each other by at most 2, such as with {3, 4, 5} or {3, 5, 5}.
scoresClump({3, 4, 5}) → true
scoresClump({3, 4, 6}) → false
scoresClump({1, 3, 5, 5}) → true
Solution:
public boolean scoresClump(int[] scores) { if (scores.length < 3) return false; for (int i = 0; i < scores.length-2; i++) { if (scores[i+2] - scores[i+1] <= 2 && scores[i+2] - scores[i] <= 2) return true; } return false; }
Couldn't you take out the "if (scores.length < 3) return false;" since if the length is less than 3, the "if" statement in the loop would never execute and thus end up hitting the final "return false;"
ReplyDeleteAlso, the array is in ascending order, so if "scores[i+2]-scores[i] <=2", "scores[i+2]-[i+1]" would automatically be true since the list is sorted.
public boolean scoresClump(int[] scores) {
ReplyDeletefor(int i = 0; i < scores.length - 2; i++) {
if(scores[i+2] - scores[i] <= 2) return true;
}
return false;
}
for(int i=scores.length-1; i>=2; i--){
ReplyDeleteif(scores[i] - scores[i-2] <=2) return true;
}
return false;
public boolean scoresClump(int[] scores)
ReplyDelete{
for(int i = 2; i < scores.length; i++)
{
if(Math.abs(scores[i-2]-scores[i]) <= 2) return true;
}
return false;
}
public boolean scoresClump(int[] scores) {
ReplyDeletefor(int i=0;i<scores.length-2;i++){
if((scores[i+2])-(scores[i])==2){
return true;
}
}
return false;
}