@XQF
2018-03-07T22:58:32.000000Z
字数 818
阅读 2137
数据结构与算法
问题描述:一个数组序列,元素取值可能是0-65535中的任意一个数,相同数值不会重复出现。0是例外,可以反复出现。设计一种算法,当从该数组序列中随意选取5个数值,判断这5个数值是否可以连续相邻。需要注意
假如取出的数列为a。
那么要是a中没有0,则a的最大值与最小值之差一定为4。
要是a中有0的话,除了0剩下的数列中的最大值与最小值之差一定小于4.
满足上述条件就OK了
,。,。像这种内部条件非常复杂的,就要哦才能够外部范围夹逼
public class Solution {
public boolean isContinuous(int[] nums) {
boolean hasZero = false;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
hasZero = true;
continue;
}
if (nums[i] > max) {
max = nums[i];
}
if (nums[i] < min) {
min = nums[i];
}
}
if (hasZero) {
if (max - min < 4) {
return true;
} else {
return false;
}
} else {
if (max - min == 4) {
return true;
} else {
return false;
}
}
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {8, 7, 6, 5, 0};
System.out.println(solution.isContinuous(nums));
}
}