[笔试题]找数组中最长和为0连续子序列

1、暴力求解法

很容易想到,用两个下标i,j来遍历数组,然后将i和j之间的元素求和,这样的方法比较简单,因为下标i和j都遍历了数组,所以时间复杂度有 O ( n 2 ) O(n^2) On2,加上求和,所以总的时间复杂度是 O ( n 3 ) O(n^3) O(n3),而空间存储只需要保留i和j还有一个最大长度的变量,所以空间复杂度为 O ( 1 ) O(1) O1.

2、动态规划法

上面方法耗时主要在求和,如果可以将部分求和的结果先保存起来,则会省不少时间,可以考虑用一个数组a,a[i]存储从下标0到i的所有元素的和,这个求和时间复杂度为 O ( n ) O(n) On。然后用两个下标遍历i,j。但是求i到j的和只需要a[j]-a[i]࿰

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 请编写一个函数,将一个数组转化成链表,并返回链表的头指针。 ```c #include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node *next; } Node; Node* array_to_linkedlist(int arr[], int size) { Node *head = NULL, *tail = NULL; for (int i = 0; i < size; i++) { Node *node = (Node*)malloc(sizeof(Node)); node->data = arr[i]; node->next = NULL; if (head == NULL) { head = tail = node; } else { tail->next = node; tail = node; } } return head; } int main() { int arr[] = {1, 2, 3, 4, 5}; int size = sizeof(arr) / sizeof(arr[0]); Node *head = array_to_linkedlist(arr, size); // 遍历链表 Node *p = head; while (p != NULL) { printf("%d ", p->data); p = p->next; } return 0; } ``` 2. 请编写一个函数,判断一个链表是否是循环链表,如果是循环链表,返回 1,否则返回 0。 ```c #include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node *next; } Node; int is_circular_linkedlist(Node *head) { if (head == NULL) { return 0; } Node *p = head, *q = head; while (q != NULL && q->next != NULL) { p = p->next; q = q->next->next; if (p == q) { return 1; } } return 0; } int main() { Node *head = (Node*)malloc(sizeof(Node)); head->data = 1; Node *p1 = (Node*)malloc(sizeof(Node)); p1->data = 2; head->next = p1; Node *p2 = (Node*)malloc(sizeof(Node)); p2->data = 3; p1->next = p2; Node *p3 = (Node*)malloc(sizeof(Node)); p3->data = 4; p2->next = p3; // 将链表变成循环链表 p3->next = head; printf("%d\n", is_circular_linkedlist(head)); return 0; } ``` 3. 请编写一个函数,实现队列的入队和出队操作。 ```c #include <stdio.h> #include <stdlib.h> #define MAX_SIZE 100 typedef struct Queue { int data[MAX_SIZE]; int front, rear; } Queue; Queue* create_queue() { Queue *q = (Queue*)malloc(sizeof(Queue)); q->front = q->rear = 0; return q; } int is_full(Queue *q) { return (q->rear + 1) % MAX_SIZE == q->front; } int is_empty(Queue *q) { return q->front == q->rear; } void enqueue(Queue *q, int x) { if (is_full(q)) { printf("Queue is full.\n"); return; } q->data[q->rear] = x; q->rear = (q->rear + 1) % MAX_SIZE; } int dequeue(Queue *q) { if (is_empty(q)) { printf("Queue is empty.\n"); return -1; } int x = q->data[q->front]; q->front = (q->front + 1) % MAX_SIZE; return x; } int main() { Queue *q = create_queue(); enqueue(q, 1); enqueue(q, 2); enqueue(q, 3); printf("%d\n", dequeue(q)); printf("%d\n", dequeue(q)); printf("%d\n", dequeue(q)); printf("%d\n", dequeue(q)); return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值