简单题

Posted curtisxiao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单题相关的知识,希望对你有一定的参考价值。

简单题二

链表操作

  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

以上是关于简单题的主要内容,如果未能解决你的问题,请参考以下文章

为啥这段代码会泄露? (简单的代码片段)

Python练习册 第 0013 题: 用 Python 写一个爬图片的程序,爬 这个链接里的日本妹子图片 :-),(http://tieba.baidu.com/p/2166231880)(代码片段

代码片段 - Golang 实现简单的 Web 服务器

创建自己的代码片段(CodeSnippet)

简单的方法来分享/讨论/协作的代码片段?

java 简单的代码片段,展示如何将javaagent附加到运行JVM进程