LeetCode刷题心得

LeetCode刷题感想

代码简洁

  • 舍弃用不到的变量

  • 如果需要判断输入为空且有返回值,那么可以直接返回输入

    • 例1:
/**
 * 我的代码
 */
public ListNode deleteDuplicates(ListNode head) {
        if(head == null) return null;  //这里可以把判断放进while的条件里
        ListNode temp = head;
        //这个变量可以省略
        int tempValue = head.val;    
        while(temp.next != null){
            if(tempValue == temp.next.val){
                if(temp.next.next != null){
                    temp.next = temp.next.next;                
                }else{
                    temp.next = null;
                }       
            }else{
                temp = temp.next;
                tempValue = temp.val;
            }
        }
        return head;
}

简化之后的代码:

public ListNode deleteDuplicates(ListNode head) {
    ListNode current = head;
    while (current != null && current.next != null) {
        if (current.next.val == current.val) {
        //我之前判断了一下next.next为空的情况,其实没必要,
        //为空的话也可以直接把空赋值给current的next
            current.next = current.next.next;
        } else {
            current = current.next;
        }
    }
    return head;
}

更为简洁的版本:

    public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null)return head;
        //递归用时最短
        head.next = deleteDuplicates(head.next);
        return head.val == head.next.val ? head.next : head;
    }
  • 例2:
  if(left.val == right.val){
            return isSymmetric(left.left, right.right) && 
            			isSymmetric(left.right, right.left);
  } 
  return false;

改善之后:

  return (t1.val == t2.val)  &&  
			isMirror(t1.right, t2.left)  &&  
			isMirror(t1.left, t2.right);

数组操作

  • 涉及到下标的一定要注意越界问题
  • 单个数组元素前移/后移问题举例:
    错误:
//后移nums1的元素
	for(int i = n; i < n + m; i ++) {
		nums1[i] = nums1[i - n];
	}

这里之所以错了是因为被替换过的数据被用来更新新的位置(类似于脏读)
改正:

//后移nums1的元素
	for(int i = m + n - 1; i >= n; i --) {
		nums1[i] = nums1[i - n];
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值