🕺作者: 主页
我的专栏 C语言从0到1 探秘C++ 数据结构从0到1 探秘Linux 算法题上机准备 😘欢迎 ❤️关注 👍点赞 🙌收藏 ✍️留言
题目
从有序顺序表中删除其值在给定值s与t之间(要求s<t)的所有元素,若s或t不合理或顺序表为空,则显示出错信息并退出运行。
算法思路
法1:按照04 删除值s与t之间的数的思路逐个判定
法2:【优化】 观察题目所给条件,给的是有序的顺序表,故只需找到小于s的最大值的下标
l
和大于t最小值的下标r
,然后将r
后面的值往l
后面覆盖,最后再维护L的长度即可。
寻找下标有两种方式:①遍历 ②折半查找
题解
①遍历
void delStoT(SqList& L, ElemType s, ElemType t) {if (L.length == 0) {printf("顺序表为空,无法操作\n");return;}else if (s >= t) {printf("s、t输入不合法\n");return;}else {int l = 0, r = 0,flag = 0;for (int i = 0; i < L.length; ++i) {if (L.data[i] < s){l = i;}if (flag == 0 && L.data[i] > t){r = i;flag = 1;}}if (l > r) {L.length = l + 1;}while (r < L.length) {l++;L.data[l] = L.data[r];r++;}L.length = l + 1;}
}
void delStoT(SqList& L, ElemType s, ElemType t) {if (L.length == 0) {printf("顺序表为空,无法操作\n");return;}else if (s >= t) {printf("s、t输入不合法\n");return;}else {int l = 0;for (int i = 0; i < L.length; ++i) {if (L.data[i] < s){l++;}else if (L.data[i] > t){L.data[l++] = L.data[i];}}L.length = l ;}
}
②折半查找
//查找大于等于target最左的位置下标
int findBigEqualLeft(SqList L, ElemType target) {int left = 0, right = L.length - 1;int ans = -1;while (left <= right) {int mid = (left + right) >> 1;if (L.data[mid] >= target) {ans = mid;right = mid - 1;}else {left = mid + 1;}}return ans;
}
//查找大于target最左的位置下标
int findSmallEqualRight(SqList L, ElemType target) {int left = 0, right = L.length - 1;int ans = -1;while (left <= right) {int mid = (left + right) >> 1;if (L.data[mid] <= target) {ans = mid;left = mid + 1;}else {right = mid - 1;}}return (ans == -1 ? ans : ans + 1);
}
void delStoT_3(SqList& L, ElemType s, ElemType t) {if (L.length == 0) {printf("顺序表为空,无法操作\n");exit(0);}else if (s >= t) {printf("s、t输入不合法\n");exit(0);}else {int findBigSFirst = findBigEqualLeft(L, s);if (findBigSFirst == -1) {return;}int findBigTFirst = findSmallEqualRight(L, t);if (findBigTFirst == -1) {return;}//没有比t大的元素if (findBigTFirst >= L.length) {L.length -= (findBigTFirst - findBigSFirst);return;}else {for (int i = findBigTFirst; i < L.length; i++) {L.data[findBigSFirst++] = L.data[i];}L.length = findBigSFirst;}}
}