Get into the habit of writing together! This is the 5th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .
Open a new pit, and plan to update the implementation of all after-school code exercises in the 23 Wangdao data structure.
Although the exams are generally written in pseudocode, I have implemented them all because of obsessive-compulsive disorder. The warehouse is here
sequence table structure
The test is used directly, generally will not let you write the structure
#define MaxSize 50
typedef struct {
ElemType data[MaxSize];
int length;
}SqList;
复制代码
2.2.3, 1
- The violent solution is generally a cycle. If the cycle fails once, it will come twice, and if it fails twice, it will be repeated three times...
- Time complexity O(n), space complexity O(1)
int del_min(SqList &list) {
if (list.length == 0) {
cout << "Error!" << endl;
return -1;
}
// 1.假设0号元素最小
int min = list.data[0];
int pos = 0;
// 2.循环找出最小元素并记录位置, 从1开始
for (int i = 1; i < list.length; i++) {
if (list.data[i] < min) {
min = list.data[i];
pos = i;
}
}
// 3.删除最小元素并用最后一个元素替换
list.data[pos] = list.data[list.length - 1];
list.length--;
return min;
}
复制代码
2.2.3, 2
- Violence is another whole array, the original array is traversed from the end and placed into the new array
- If the space complexity is O(1), loop from the beginning to the middle, and exchange the head and tail elements
- Even or odd number of elements, loop to the middle, all
< length/2
, because if the length is 4 or 5, the loop stops when the subscript is 1, and when it is 5, the middle element (subscript 2) does not need to move. - Time complexity O(n)
void reverse(SqList &list) {
for (int i = 0; i < list.length / 2; i++) {
// 不让用swap()的话,可以定义一个辅助变量来交换
swap(list.data[i], list.data[list.length - 1 - i]);
}
}
复制代码
2.2.3, 3
- Violence is to complete another array, loop through and put all elements not equal to x into the new array
- Time complexity O(n), space complexity O(1) requires one loop to solve
- Throw all elements equal to x to the end, and then subtract the length
- Reverse: that is, throw all elements that are not equal to x to the front, and naturally the elements that are equal to x are behind.
void del_x(SqList &list, int x) {
int k = 0;
for (int i = 0 ; i < list.length ; i++) {
// 1.把所有要保存的值都放在前面
if (list.data[i] != x) {
list.data[k++] = list.data[i];
}
}
// 2.直接扔掉后面的元素
list.length = k;
}
复制代码
- One loop -> double pointer
- Similar to quicksort, moving from both ends to the middle, swapping the x on the left with the non-x on the right
// 太麻烦了,不如上一个方法
void del_x_2(SqList &list, int x) {
int i = -1, j = list.length, k = 0;
while (i < j) {
while (list.data[++i] != x);
while (list.data[--j] == x) k++;
if (i < j) {
swap(list.data[i], list.data[j]);
k++;
}
}
list.length -= k;
}
复制代码