码迷,mamicode.com
首页 > 其他好文 > 详细

简单题

时间:2019-04-15 09:15:05      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:range   class   __init__   turn   反转链表   init   ntp   fast   +=   

简单题二

链表操作

  1. (leetcode 204) 求解质数个数

    求解质数,使用筛法;

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n == 0 or n==1 or n==2:
            return 0
        prime = [True for i in range(n)]
        for i in range(2,n):
            tmp = i
            if prime[tmp]:
                j = 2
                while tmp*j < n:
                    prime[tmp*j] = False
                    j += 1
        res = 0
        for i in range(2,n):
            if prime[i]:
                res += 1
        return res
  1. (leetcode 206) 反转链表

    很简单的一道题,但是总是不能理清next的关系;
    为什么 head = head.next 与 p.next = new_head 的顺序 不饿能颠倒?

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        new_head = None
        while head:
            p = head
            head = head.next
            p.next = new_head
            new_head = p
        return new_head
  1. (leetcode 876) 寻找链表的中间节点

    快慢指针貌似在链表操作中经常使用;

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def middleNode(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        fast = slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        return slow
  1. (leetcode 234)判断一个链表是否为回文链表

    需要熟悉链表的基本操作,本题涉及链表反转和找链表的中间点;

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        fast = slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        new_head = None
        # while slow:
        #     p = slow.next
        #     slow.next = new_head
        #     new_head = slow
        #     slow = p
        while slow:
            p = slow
            slow = slow.next
            p.next = new_head
            new_head = p
        while new_head:
            # print(new_head.val)
            if new_head.val != head.val:
                return False
            new_head = new_head.next
            head = head.next
        return True

简单题

标签:range   class   __init__   turn   反转链表   init   ntp   fast   +=   

原文地址:https://www.cnblogs.com/curtisxiao/p/10708449.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!