牛客网刷题第四天 | HJ51 输出单向链表中倒数第k个结点、HJ55 挑7

HJ51 输出单向链表中倒数第k个结点

牛客网大佬思路:采用头插法实现,这样可以得出结论,倒数第k个 === 整数第k个

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int length = in.nextInt();
            ListNode head = new ListNode(-1);
            for (int i = 0; i < length; i++) {
                int value = in.nextInt();
                ListNode node = new ListNode(value);
                node.next = head.next;
                head.next = node;
            }
            int num = in.nextInt();
            while (num > 0) {
                head = head.next;
                num--;
            }
            System.out.println(head.value);
        }
    }
}

class ListNode {
    Integer value;
    ListNode next;

    public ListNode(Integer value) {
        this.value = value;
        this.next = null;
    }
}

正常思路:

尾插法,即每次新结点在链表的结尾插入,采用双指针法,快指针与慢指针相差k-1个,当快指针到达链表尾部时,慢指针所指即为倒数第k个节点

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int length = in.nextInt();
            ListNode head = new ListNode(-1);
            ListNode tmp = head;
            for (int i = 0; i < length; i++) {
                int value = in.nextInt();
                ListNode node = new ListNode(value);
                tmp.next = node;
                tmp = tmp.next;
            }
            int num = in.nextInt();
            ListNode fast = head.next;
            ListNode slow = head.next;
            while (num > 1) {
                fast = fast.next;
                num--;
            }
            while (fast.next != null) {
                fast = fast.next;
                slow = slow.next;
            }
            System.out.println(slow.value);
        }
    }
}

class ListNode {
    Integer value;
    ListNode next;

    public ListNode(Integer value) {
        this.value = value;
        this.next = null;
    }
}

HJ55 挑7

如果对7取余为0,结果++,否则观察是否包含7

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        int res = 0;
        for (int i = 7; i <= num; i++) {
            if (i % 7 == 0) {
                res++;
            } else if (String.valueOf(i).contains("7")) {
                res++;
            }
        }
        System.out.println(res);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值