LeetCode Day13


前言

今天是寒假LeetCode刷题打卡的第十三天,继续坚持、继续加油!也希望我的博文能够帮助到大家,若有疑问,可以随时私信Call我!

一、160 相交链表

1. 题目描述

难度:简单

160 相交链表-leetcode官网

2. 代码实现

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA==null||headB==null)
            return null;
        ListNode i=headA;
        ListNode j=headB;
        while(i!=null||j!=null)
        {
            if(i==null)
                i=headB;
            if(j==null)
                j=headA;
            if(i==j)
                return i;
            i=i.next;
            j=j.next;
            
        }
        return null;
    }
}

二、169. 多数元素

1. 题目描述

难度:简单

169. 多数元素-leetcode官网

2. 代码实现

class Solution {
    public int majorityElement(int[] nums) {
        Map<Integer,Integer> map=new HashMap<Integer,Integer>();
        for(int i=0;i<nums.length;++i)
        {
            if(map.containsKey(nums[i]))
            {
                map.replace(nums[i],map.get(nums[i])+1);
            }
            else
            {
                map.put(nums[i],1);
            }
        }
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if(entry.getValue()>nums.length/2)
                return entry.getKey();
        }
        return nums[0];
    }
}

注:本题我采用的是hash法来做的,时间和空间复杂度都是o(n)。我测试了一下排序法,在leetcode上的时间反而比hash要快。我估计是示例的数据量太小了的原因。实际上,我认为我们做的时候应该关心时间复杂度和空间复杂度,而不用太关心leetcode的击败人数。

三、206. 反转链表

1. 题目描述

难度:简单

206. 反转链表-leetcode官网

3. 代码实现

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null)
            return null;
        ListNode top=new ListNode();
        top.next=head;
        ListNode i,j;
        i=head;
        while(i.next!=null)
        {
            j=i.next;
            i.next=j.next;
            j.next=top.next;
            top.next=j;
        }
        return top.next;
    }
}

注:头插法。

总结

以上就是今天 LeetCode寒假刷题 Day13 所做的三道题。若有任何疑问,欢迎私信或评论区留言鸭!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值