arrays - 检查是否存在索引 k 使得数组 A[] 的元素顺时针移动形成一个反向双调数组
问题描述
检查是否存在索引,使得由索引顺时针移动0 <= k < n - 2
的数组元素构成一个反向双调数组。我在O(n)时间复杂度中做到这一点的方法:A[]
k
bool is_antibitonicable(int A[], int n) {
// returns if there is such index k that
// after moving clockwise k elements of array
// A[], that array is reverse bitonic
// - strictly decreasing then strictly
// increasing
if (n < 3)
return false;
// if is_increasing[i] == 1 means this part of A[] is increasing,
// == 0 means that part of A[] is decreasing, == -1 default
int is_increasing[3] = { -1, -1, -1 };
for (int i = 0, j; i < n - 1;) {
if (A[i] < A[i + 1]) { // if A[] is increasing
j = 0;
while (j < 3 && is_increasing[j] != -1)
j++;
if (j == 3)
return false;
is_increasing[j] = 1;
while (i < n - 1 && A[i] < A[i + 1])
i++;
}
else if (A[i] > A[i + 1]) { // check if decreasing
j = 0;
while (j < 3 && is_increasing[j] != -1)
j++;
if (j == 3)
return false;
is_increasing[j] = 0;
while (i < n - 1 && A[i] > A[i + 1])
i++;
}
else // sequence of A[] is neither increasing nor decreasing
return false;
}
// if A[] is only increasing/decreasing
if (is_increasing[1] == is_increasing[2])
return false;
// if A[] is increasing->decreasing->increasing check if increasing
// parts can be merged into one increasing sequence
if (is_increasing[0] == 1 && is_increasing[1] == 0 && is_increasing[2] == 1)
return (A[0] > A[n - 1]);
// decreasing->increasing->decreasing
if (is_increasing[0] == 0 && is_increasing[1] == 1 && is_increasing[2] == 0)
return (A[0] < A[n - 1]);
return true; // increasing -> decreasing or opposite
}
如果有人可以查看我的解决方案并评论它是否正确或如何做得更好,我将非常高兴,任何反馈将不胜感激。
解决方案
您的解决方案看起来不错,但确实不正确return false
// if A[] is only increasing/decreasing
。这样的序列总是可以通过在正确(适当的)方向上旋转一个而变成第一个减少然后增加一个。
推荐阅读
- amazon-web-services - 如何将现有的 Elasticsearch 数据从字符串转换为数字
- javascript - 创建新的城市状态对象
- sharepoint-online - Power Apps 在 SharePoint 列表列中存储图像的最佳方法
- wpf - 当我用鼠标拖动窗口时如何调整整个窗口的大小
- wordpress - 主题中的未知 CSS 代码导致图像模糊
- django - 部署我的 Django 应用程序时如何修复 heroku 连接错误
- python - SQLAlchemy 在使用 contains_eager 时加载不相关的缓存对象
- javascript - 如何在 Wordpress 页面上呈现 React?
- sql - 在 SQL 中使用“Pivot”将行转换为列
- ios - Swiftui 如何在 foreach 循环中对整行使用 Tap Gesture