今天在刷公众号时,发现了两道很经典,很常见的算法题目。用到的解题方法都是很常见的。下面就让我们来看看这两道题目吧
第一道题目:链表题,用到的解题方法也是非常经典的双指针。
题目:
实现一个函数,查找链表的倒数第k个结点
思路:使用两个指针,第一个指针先指向第k个结点,然后两个指针同时移动,第一个指针移动到末尾的时候,第二个指针刚好位于倒数第k个位置
源代码:
#include<iostream>
using namespace std;
struct LinkNode
{
int val;
LinkNode* next;
};
LinkNode* createLink(int arr[], int n)
{
LinkNode* r, * s, * L;
L = (LinkNode*)malloc(sizeof(LinkNode));
L->next = nullptr;//头结点刚开始指针域是指向空的
r = L;
for (int i = 0; i < n; i++)
{
s = (LinkNode*)malloc(sizeof(LinkNode));
if (s == nullptr)//要判断是否创建成功
{
return nullptr;
}
s->val = arr[i];
r->next = s;
r = s;
r->next = nullptr;//尾指针指针域指向空
}
return L;
}
LinkNode* lastKNode(LinkNode* head, int k)
{
if (head == NULL || k <= 0)
{
return NULL;
}
LinkNode* firstPoint = head;
LinkNode* secondPoint = head;
int index = 0;
while (firstPoint->next != NULL && index < k)
{
firstPoint = firstPoint->next;
index++;
}
//链表长度小于k,直接return NULL
/*if (index < k - 1)
{
return NULL;
}*/
while (firstPoint->next != NULL)
{
firstPoint = firstPoint->next;
secondPoint = secondPoint->next;
}
return secondPoint;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
LinkNode* head = createLink(arr, 5);
LinkNode* result = lastKNode(head, 3);
if (result != NULL) {
cout << result->val << endl;
}
system("pause");
return 0;
}
程序执行图:
第二道:第二道题是关于数组的问题,数组问题相对来说会难度小亿点点(当然难的也一大推)
题目:
实现一个函数,找出数组中出现次数超过一半的元素
思路:默认第一个元素为找到的元素result,设置times变量为1,遍历数组,如果后面的元素等于result,times加1,如果后面的元素不等于result,times减1,如果times为0,则把result替换为当前元素
源代码:
#include<iostream>
using namespace std;
int moreThanHalfNumber(int arr[], int length)
{
if (arr == NULL || length <= 0) {
return -1;
}
if (length == 1) {
return arr[0];
}
int times = 1;
int result = arr[0];
for (int i = 1; i < length; i++) {
if (times == 0) {
result = arr[i];
times = 1;
}
else if (arr[i] == result) {
times++;
}
else {
times--;
}
}
//校验是否次数超过一半
int resTimes = 0;
for (int i = 0; i < length; i++) {
if (arr[i] == result) {
resTimes++;
}
}
if (resTimes * 2 > length) {
return result;
}
return -1;
}
int main()
{
int arr[8] = { 3, 2, 8, 2, 2, 2, 6, 2 };
int result = moreThanHalfNumber(arr, 8);
cout << result <<endl;
return 0;
}
程序执行图:
本贴为博主亲手整理。如有错误,请评论区指出,一起进步。谢谢大家的浏览.
796

被折叠的 条评论
为什么被折叠?



