I need to return the minimum gap between numbers in an array. Gap as in, if a[2] = 3, and a[3] = 6, the gap would be 3. I need to put the return statement elsewhere but I don't know where to put it because then the smallestGap
would not be accessible. a
stands for the array you would put in. I don't have a full class because this problem is on practice-it.
This is what I have so far:
public static int minGap(int[] a){
for(int i = 0; i < a.length; i++){
int smallestGap = a[i+ 1] - a[i];
int gap = a[i+1] - a[i];
if(gap < smallestGap){
smallestGap = gap;
return smallestGap;
}
}
//if array has less than two elements return 0
}
Thank you.
I don't get your problem exactly. Start from a smallestGap
defined as larger than any other possible gap, so you can then return it. Eg:
int smallestGap = Integer.MAX_VALUE;
for (int i = 0; i < a.length - 1; ++i) {
int gap = a[i+1] - a[i];
smallestGap = Math.min(gap, smallestGap);
}
return smallestGap;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.