几道算法题:
第一题:
// MS.cpp : 定义控制台应用程序的入口点。
//
#include <iostream>
using namespace std;
/*函数功能:求正整数的平方根,要求误差在0.001
思路:二分法
*/
//在误差范围内比较两个数
int dcmp(double x) {
if (x < -1e-3)
return -1;
return x > 1e-3;
}
double sqrtHelper(double left, double right, double n) {
double mid = (left + right) / 2;
if (dcmp(mid*mid - n) == 0)
return mid;
else if (dcmp(mid*mid - n) < 0)
return sqrtHelper(mid, right, n);
else
return sqrtHelper(left, mid, n);
}
double mySqrt(double n) {
return sqrtHelper(0, n, n);
}
int main() {
int a = 5, b = 3, c = 9;
double as = mySqrt(a);
double bs = mySqrt(b);
double cs = mySqrt(c);
cout << as << endl;
cout << bs << endl;
cout << cs << endl;
return 0;
}
第二题:
#include <iostream>
using namespace std;
/*函数功能:判断两个链表是否相交
思路:考虑几种情况:1.两个链表都不带环 2.其中一个带环(定不相交)3.两个都带环
*/
struct LinkNode {
int val;
LinkNode *next;
LinkNode(int x) : val(x), next(NULL){}
};
//两个链表都没有环,看尾指针是否相等
int isSimpleJoined(LinkNode *h1, LinkNode *h2) {
LinkNode *p1 = h1, *p2 = h2;
while (p1->next != NULL)
p1 = p1->next;
while (p2->next != NULL)
p2 = p2->next;
return p1 == p2;
}
//使用快慢指针判断链表是否有环
LinkNode *testCycle(LinkNode *h1) {
LinkNode *slow = h1, *fast = h1;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
return slow;
}
return NULL;
}
int isJoined(LinkNode *h1, LinkNode *h2) {
LinkNode *c1 = testCycle(h1);
LinkNode *c2 = testCycle(h2);
//两链表都无环
if (c1 == NULL && c2 == NULL)
return isSimpleJoined(h1, h2);
//只有一个链表有环
else if (c1 == NULL || c2 == NULL)
return 0;
//两个链表都有环,c1,c2都在环中,若c1绕环一圈没遇到c2则两个链表不相交
LinkNode *p1 = c1;
while (1) {
if (c1 == c2)
return 1;
p1 = p1->next->next;
c1 = c1->next;
if (p1 == c1)
return 0;
}
}
int main() {
LinkNode *h1 = new LinkNode(1);
h1->next = new LinkNode(2);
h1->next->next = new LinkNode(3);
h1->next->next->next = new LinkNode(4);
h1->next->next->next->next = h1->next->next->next;
LinkNode *h2 = new LinkNode(5);
h2->next = new LinkNode(6);
h2->next->next = h1->next->next;
int join = isJoined(h1, h2);
cout << join << endl;
return 0;
}
第三题:
#include <iostream>
#include <limits.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {};
};
/*函数功能:求二叉树的最大子树和
*/
int maxS = INT_MIN;
int maxTreeSum(TreeNode *root) {
if (root == NULL)
return 0;
int left = maxTreeSum(root->left);
int right = maxTreeSum(root->right);
int sum = left + right + root->val;
maxS = max(sum, maxS);
return sum;
}
int main() {
TreeNode *root = new TreeNode(10);
root->left = new TreeNode(-20);
root->right = new TreeNode(5);
root->left->left = new TreeNode(-7);
root->left->right = new TreeNode(8);
root->right->left = new TreeNode(7);
root->right->right = new TreeNode(9);
maxTreeSum(root);
cout << maxS << endl;
return 0;
}