酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。在c语言中用set实现

以下是一个使用 C 语言的`set`(通过二叉搜索树实现)来解决此问题的示例代码: ```c #include <stdio.h> #include <stdlib.h> // 二叉搜索树的节点结构 typedef struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; } TreeNode; // 创建新节点 TreeNode* createNode(int val) { TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode)); newNode->val = val; newNode->left = NULL; newNode->right = NULL; return newNode; } // 插入节点到二叉搜索树 TreeNode* insert(TreeNode* root, int val) { if (root == NULL) { return createNode(val); } if (val < root->val) { root->left = insert(root->left, val); } else if (val > root->val) { root->right = insert(root->right, val); } return root; } // 中序遍历二叉搜索树 void inorderTraversal(TreeNode* root) { if (root!= NULL) { inorderTraversal(root->left); printf("%d ", root->val); inorderTraversal(root->right); } } // 查找第三大的数 int findThirdLargest(int arr[], int size) { TreeNode* root = NULL; for (int i = 0; i < size; i++) { root = insert(root, arr[i]); } int count = 0; int result = -1; inorderTraversal(root); printf("\n"); TreeNode* curr = root; while (curr!= NULL) { if (curr->right == NULL) { if (++count == 3) { result = curr->val; break; } curr = curr->left; } else { TreeNode* successor = curr->right; while (successor->left!= NULL && successor->left!= curr) { successor = successor->left; } if (successor->left == NULL) { successor->left = curr; curr = curr->right; } else { successor->left = NULL; if (++count == 3) { result = curr->val; break; } curr = curr->left; } } } if (result == -1) { result = root->val; } return result; } int main() { int arr[] = {2, 2, 3, 1}; int size = sizeof(arr) / sizeof(arr[0]); int thirdLargest = findThirdLargest(arr, size); printf("第三大的数是: %d\n", thirdLargest); return 0; } ``` 这段代码首先创建了一个二叉搜索树来存储数组中的元素,然后通过遍历树来找到第三大的数。如果不存在第三大的数,则返回最大的数。 [2024-09-12 23:09:16 | AI写代码神器 | 737点数解答]

相关提问