如何确定序列是否为双音?
问题内容:
如果序列单调增加然后单调减少,或者可以循环移位单调增加然后单调减少,则该序列为双音调。例如,序列(1、4、6、8、3,-2),(9、2,-4,-10,-5)和(1、2、3、4)是双音调的,但是(1
(3、12、4、2、10)不是重音。
如何确定给定序列是否为双音?
我有以下意见。我们可以走到 n / 2 ,其中 n 是数组的长度,然后检查是否
(a[i] < a[i + 1]) and (a[n - i - 1] < a[n-1 - (i + 1)])
这样对吗?
问题答案:
双音序列:
/\
/ \
\/
不是双音序列:
/\
/ \ / (higher than start)
\/
显然,如果方向改变两次以上,我们将无法获得双音序列。
如果方向变化少于两次,则必须具有双音序列。
如果方向有两个变化,我们可以有一个双音序列。考虑上面的两个ascii图像。显然,具有两个方向变化的序列将匹配其中一种模式(允许反射)。因此,我们通过比较第一个和最后一个元素来设置初始方向。由于这些可以相同,因此我们使用不等于最后一个元素的第一个元素。
这是Java的实现:
public static Boolean bitonic(int[] array) {
if (array == null) return false;
if (array.length < 4) return true;
Boolean dir;// false is decreasing, true is increasing
int pos = 0, switches = 0;
while (pos < array.length) {
if (array[pos] != array[array.length - 1])
break;
pos++;
}
if (pos == array.length) return true;
//pos here is the first element that differs from the last
dir = array[pos] > array[array.length - 1];
while (pos < array.length - 1 && switches <= 2) {
if ((array[pos + 1] != array[pos]) &&
((array[pos + 1] <= array[pos]) == dir)) {
dir ^= true;
switches++;
}
pos++;
}
return switches <= 2;
}