leetcode coding_tips

系列博客目录



1. for循环更新部分

不能下面代码的第二行,只能是第一行。

j += label==0 ? ((numRows-i-1)*2) : i*2)
j = j + label==0 ? ((numRows-i-1)*2) : i*2)
j = j + label==0 ? ((numRows-i-1)*2) : i*2

这里的问题在于,条件表达式 label == 0 ? ((numRows-i-1)*2) : i*2 的优先级低于 + 运算符。表达式会先计算 j + label 再比较是否== 0,它的结果是一个布尔值(TrueFalse),然后 ? 运算符(条件运算符)会根据该布尔值选择两部分中的一部分(((numRows-i-1)*2)i*2),接着赋值给j

2.没有头结点可以自己创建一个头结点来简化问题。

19.删除链表的倒数第 N 个结点
链接

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode root = new ListNode();
        root.next = head;
        int count = n+1;
        head = root;
        ListNode res = head;
        while(head!=null){
            if(count>0){
                count--;
            }else {
                res = res.next;
            }
            head = head.next;
        }
        res.next = res.next.next;
        return root.next;
    }
}

3.链表中while循环判定条件可以是head!=null或者head.next!=null,要根据情况判定。

4.数组中我们经常用当前节点和前面节点作比较,链表中用当前节点的后面结点进行比较,这样方便删除节点。

82题。

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null) return null;
        ListNode dummyNode = new ListNode(0,head);
        ListNode cur = dummyNode;
        while(cur.next!= null && cur.next.next != null){
            if(cur.next.val == cur.next.next.val){
                int x = cur.next.val;
                while(cur.next!=null && cur.next.val==x ){
                    cur.next = cur.next.next;
                }
            }else {
                cur = cur.next;
            }
        }
        return dummyNode.next;
    }
}

5.line = new ArrayList<>();用于清空链表

6.返回空数组 return new int[0]

7.

8.

9.

10.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值