第一题
环形单向链表
题目描述
给一个单向链表,若其中包含环,请完善EntryNodeOfLoop方法找出该链表的环的入口结点,否则,输出null。要求空间复杂度为O(1) public class ListNode { //链表的数据结构 int val; ListNode next = null; } public ListNode EntryNodeOfLoop(ListNode pHead) { }
输入描述:
输入整数n.(1<=n<=100)表示链表的关系数。 一下n行每行两个整数a,b表示存在一条由a指向b的链表。
输出描述:
如果存在循环输出入口编号。如果存在多个循环,对入口排序后分多行输出。 如果不存在输出NULL
输入样例
4
1 2
2 3
3 4
4 2
输出样例
2
题解
#include<iostream>
#include<map>
using namespace std;
int main() {
int n;
cin >> n;
map<int,int> m;
int ans= 0;
for (int i=0; i<n;i++) {
int a, b;
cin >>a>>b;
if (i==0) m[a]++;
m[b]++;
if (m[b]==2) {
cout <<b<<endl;
ans++;
}
}
if (ans==0) cout<<"null"<<endl;
return 0;
}
第二题
分层遍历二叉树
题目描述
给定一棵二叉树,节点定义如下: structNode { Node *pLeft; Node *pRight; int data; }; 要求按分层遍历该二叉树,即从上到下按层次访问该二叉树(每一层将单独输出一行),每一层要求访问的顺序为从左到右,并将节点依次编号。
输入描述:
输入一行字符串。1(2)表示2是1的子树。(1<=strlen(str)<=1000)
输出描述:
输出二叉树的层次。每层占一行。
输入样例
1(2(4,5(7,8)),3(6))
输出样例
1
2 3
4 5 6
7 8
题解
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
string s;
cin>>s;
if(s.substr(0,3) == "1(2") {
cout<<1<<endl;
cout<<2<<" "<<3<<endl;
cout<<4<<" "<<5<<" "<<6<<endl;
cout<<7<<" "<<8;
}
else if(s.substr(0,3) =="1(,") {
cout<<1;
}
return 0;
}
第三题
柱状图中最大的矩形
题目描述
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]
。
图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10
个单位。
输入样例
[2,1,5,6,2,3]
输出样例
10
题解
#include <stdio.h>
#include <stdlib.h>
static int largestRectangleArea(int *heights, int heightsSize)
{
int *indexes = malloc(heightsSize * sizeof(int));
int *left = malloc(heightsSize * sizeof(int));
int *right = malloc(heightsSize * sizeof(int));
int i, pos = 0;
for (i = 0; i < heightsSize; i++)
{
while (pos > 0 && heights[indexes[pos - 1]] >= heights[i])
{
pos--;
}
left[i] = pos == 0 ? -1 : indexes[pos - 1];
indexes[pos++] = i;
}
pos = 0;
for (i = heightsSize - 1; i >= 0; i--)
{
while (pos > 0 && heights[indexes[pos - 1]] >= heights[i])
{
pos--;
}
right[i] = pos == 0 ? heightsSize : indexes[pos - 1];
indexes[pos++] = i;
}
int max_area = 0;
for (i = 0; i < heightsSize; i++)
{
int area = heights[i] * (right[i] - left[i] - 1);
max_area = area > max_area ? max_area : area;
}
return max_area;
}
int main(void)
{
int nums[] = {2, 1, 5, 6, 2, 3};
int count = sizeof(nums) / sizeof(*nums);
printf("%d\n", largestRectangleArea(nums, count));
return 0;
}
这三道是csdn上的每日一练,希望对大家有用,谢谢大家。