环形链表_相交链表_多数元素(java语言)

科技资讯 投稿 11400 0 评论

环形链表_相交链表_多数元素(java语言)

环形链表

问题:

代码实现:

public class Solution {
    public boolean hasCycle(ListNode head {
        Set<ListNode> set = new HashSet<>(;
        while (head != null{
            if (set.contains(head
                return true;
            set.add(head;
            head = head.next;
        }
        return false;
    }
}

相交链表

力扣160题

代码实现:

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB {
        Set<ListNode> set = new HashSet<>(;
        ListNode temp = headA;//头指针不方便移动,赋值给temp
        while (temp != null{
            set.add(temp;
            temp = temp.next;
        }
        temp = headB;
        while (temp != null{
            if (set.contains(temp//如果保护这个节点,则直接返回这个节点。
                return temp;
            temp = temp.next;
        }
        return null;
    }
}

多数元素

力扣169题

代码实现:

class Solution {
    public int majorityElement(int[] nums {
        Map<Integer, Integer> map = new HashMap<>(;
        //把数组中的每个数字和对应出现的次数存放到map中
        for(Integer i : nums{
            Integer count = map.get(i;
            count = count == null ? 1 : ++count;
            map.put(i,count;
        }
        //把数组中
        for(Integer i : map.keySet({
            Integer count = map.get(i;
            if (count > nums.length / 2
                return i;
        }
        return 0;
    }
}

编程笔记 » 环形链表_相交链表_多数元素(java语言)

赞同 (57) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽