408 King's Road Data Structure After-School Exercises (3)

Get into the habit of writing together! This is the 7th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

I plan to update the implementation of all after-school code exercises in the 23 King's Road data structure. Although the exams are generally written in pseudocode, I have implemented all of them for obsessive-compulsive disorder. The warehouse is here.

  • Linear table

2.2.3, 6

image.png

  • Ordered list ➡️ same elements are arranged together
  • Violence, open a new array and store different elements in
  • Two pointers are required to operate two arrays respectively
  • Time complexity O(n), space complexity O(n)
void del_same(SqList &list) {
  if (list.length == 0) return;
  
  // 1.新开一个数组
  SqList copied = list;
  copied.data[0] = list.data[0];

  // 2.把不同元素存入
  int k = 0;
  for (int i = 1; i < list.length; i++) {
    if (list.data[k] != copied.data[i]) {
      copied.data[++k] = list.data[i];
    }
  }

  // 3.新换旧
  copied.length = k + 1;
  list = copied;
}
复制代码
  • Think about it, you don't really need two arrays, just double pointers
  • The former is stored, the latter is judged
void del_same2(SqList &list) {
  if (list.length == 0) return;

  int k = 0;
  for (int i = 1; i < list.length; i++) {
    if (list.data[k] != list.data[i]) {
      list.data[++k] = list.data[i];
    }
  }
  list.length = k + 1;
}
复制代码

2.2.4, 7

image.png

  • This kind of question is too typical, merging ordered list and merging ordered linked list, it is recommended to recite the full text hh
  • Loop, take the smaller of the two and put it into the result table
  • The last table has leftovers, and the remaining parts are added to the result table
SqList merge(SqList A, SqList B) {
  SqList C;
  if (A.length + B.length > MaxSize) {
    cout << "ERROR!" << endl;
    return C;
  }

  int i = 0, j = 0, k = 0;
  // 1.两两比较,小的存入结果表
  while (i < A.length && j < B.length) {
    if (A.data[i] <= B.data[j])
      C.data[k++] = A.data[i++];
    else
      C.data[k++] = B.data[j++];
  }

  // 2.剩下的全部加入结果表,两个循环只会有一个运行
  while (i < A.length) 
    C.data[k++] = A.data[i++];
  while (i < B.length) 
    C.data[k++] = B.data[j++];

  // 3.返回结果表
  C.length = k;
  return C;
}
复制代码
  • Add merge sort
void merge_sort(int l, int r) {
  if (l >= r) return;

  int mid = (l+r) >> 1;
  merge_sort(l, mid);
  merge_sort(mid+1, r);		

  int k = 0, i = l, j = mid+1;
  while (i <= mid && j <= r) {
    if (q[i] <= q[j]) 
      tmp[k++] = q[i++];
    else 
      tmp[k++] = q[j++];
  }
  
  while (i <= mid) 
    tmp[k++] = q[i++];
  while (j <= r) 
    tmp[k++] = q[j++];

  for (i = l, j = 0; i <= r; i++, j++) 
    q[i++] = tmp[j++];
}
复制代码

Guess you like

Origin juejin.im/post/7084413193400877070