前言
今天是寒假LeetCode刷题打卡的第十三天,继续坚持、继续加油!也希望我的博文能够帮助到大家,若有疑问,可以随时私信Call我!
一、160 相交链表
1. 题目描述
难度:简单
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. 题目描述
难度:简单
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. 题目描述
难度:简单
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 所做的三道题。若有任何疑问,欢迎私信或评论区留言鸭!