算法荷兰国旗问题java - 左神算法基础课04 - Kaiqisan

大家好,都吃晚饭了吗?我是Kaiqisan,是一个已经走出社恐的一般生徒,今天再来康康链表的算法

问题

荷兰国旗问题 — 给一串链表,再给一个数字,让做左部分的值比这个数字小,右部分的值比这个数字大,且不修改它们的相对位置。

比如

flag = 3
3 -> 2 -> 1 -> 5 -> 6 -> 7 -> 4
变换后
2 -> 1 -> 3 -> 5 -> 6 -> 7 -> 4

进阶要求:时间复杂度 O(N) 空间复杂度O(1)

暗示不能使用额外空间创建链表

解答

思路,先遍历第一遍链表,找第一个比参考值小的点和第一个比参考值大的点和第一个等于参考值的节点,有就尽量找,没有就放弃不强求,(起码可以找到一个
找到之后再次遍历链表,比较当前的值和参考值,然后再进行如下连接(不使用上面的案例)
在这里插入图片描述
然后把Less Equal More 依次链接起来

	// 第一个参数为输入的链表,第二个参数为判定值
	static LinkList exeSort(LinkList head, int judgeVal) {
        LinkList Less = null;
        LinkList Equal = null;
        LinkList More = null;

        // 头
        LinkList _Less = null;
        LinkList _Equal = null;
        LinkList _More = null;

        LinkList _head = head;

        while (_head != null) {
            if (_head.val > judgeVal && More == null) {
                More = _head;
                _More = More;
            }

            if (_head.val < judgeVal && Less == null) {
                Less = _head;
                _Less = Less;
            }

            if (_head.val == judgeVal && Equal == null) {
                Equal = _head;
                _Equal = Equal;
            }
            _head = _head.next;
        }

        _head = head;
        LinkList temp;
        while (_head != null) {
            temp = _head;
            _head = _head.next;
            if (temp.val > judgeVal && temp != More) {
                More.next = temp;
                More = More.next;
            } else if (temp.val < judgeVal && temp != Less) {
                Less.next = temp;
                Less = Less.next;
            } else if (temp.val == judgeVal && temp != Equal) {
                Equal.next = temp;
                Equal = Equal.next;
            }
            temp.next = null;
        }

        LinkList a = new LinkList(0);
        LinkList _a = a;
        if (Less != null) {
            a.next = _Less;
            a = doRead(a);
        }
        if (Equal != null) {
            a.next = _Equal;
            a = doRead(a);
        }
        if (More != null) {
            a.next = _More;
        }
        return _a.next;
    }

总结

链表中的命名可能要起得尽量普通些,因为如果您要追求极致的内存空间的话,需要找到前面已经使用完成的变量,实现“废物利用”。如果您的名字起得太有目的性的话在后面的使用中容易产生理解上的困难。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kaiqisan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值