Leetcode刷题

206反转链表

采用双指针的思想,pre指针刚开始指向null,cur指针指向头,将cur指针指向pre,但在这之前需要将cur的下一个保存起来,因为cur指向pre的时候和后面的值断开了。

class Solution {
    public ListNode reverseList(ListNode head) {
       //反转链表
        ListNode  pre=null;
        ListNode cur=head;
        while (cur!=null){
            ListNode next=cur.next; //指向下一个
            cur.next=pre;
            pre=cur;
            cur=next;
        }
        return  pre;
    }
}

104二叉树的最大深度

class Solution {
    public int maxDepth(TreeNode root) {
      //二叉树的最大深入
        // 给的是层序遍历
        //dfs遍历结果了
        if(root==null){
            return 0;
        }
        int left =maxDepth(root.left)+1;
        int right=maxDepth(root.right)+1;
        return Math.max(left,right);
    }

}

1两数之和

原来是on方的时间复杂度,通过hashmap将时间复杂度变为on;

import java.util.HashMap;

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int[] twoSum(int[] nums, int target) {
      Map<Integer,Integer> mp=new HashMap<>();
      int a[]=new int[2];
      for(int i=0;i<nums.length;i++){
          //把值给访进去
          if( mp.containsKey(target-nums[i])){
              a[0]=mp.get(target-nums[i]);
              a[1]=i;
              return  a;
          }
          mp.put(nums[i],i);
      }
      return  a;
    }
}

560和为k的子数组

第一题的变式;

public class Solution {
    public int subarraySum(int[] nums, int k) {
        int count = 0, pre = 0;
        HashMap < Integer, Integer > mp = new HashMap < > ();
        mp.put(0, 1); //长度为0,直接为1个
        for (int i = 0; i < nums.length; i++) {
            pre += nums[i]; //求前缀和
            if (mp.containsKey(pre - k)) {
                count += mp.get(pre - k);
            }
            mp.put(pre, mp.getOrDefault(pre, 0) + 1);
        }
        return count;
    }
}
  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

想要打 Acm 的小周同学呀

您的支持是我最大的动力

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

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

打赏作者

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

抵扣说明:

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

余额充值