算法日记(一)

今天在刷公众号时,发现了两道很经典,很常见的算法题目。用到的解题方法都是很常见的。下面就让我们来看看这两道题目吧

第一道题目:链表题,用到的解题方法也是非常经典的双指针。

题目:

实现一个函数,查找链表的倒数第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;
}

程序执行图:

本贴为博主亲手整理。如有错误,请评论区指出,一起进步。谢谢大家的浏览.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值