Leetcode 算法题24

234Palindrome Linked List

判断一个链表是否左右对称,用O(n)的时间和O(1)的内存

我的代码:

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

class Solution:
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        ans = []
        head
        while head:
            ans.append(head.val)
            head = head.next
        return ans == ans[::-1]

大神的代码:

#Solution 1: Reversed first half == Second half?

#Phase 1: Reverse the first half while finding the middle.
#Phase 2: Compare the reversed first half with the second half.
def isPalindrome(self, head):
    rev = None
    slow = fast = head
    while fast and fast.next:
        fast = fast.next.next
        rev, rev.next, slow = slow, rev, slow.next
    if fast:
        slow = slow.next
    while rev and rev.val == slow.val:
        slow = slow.next
        rev = rev.next
    return not rev
#Solution 2: Play Nice

#Same as the above, but while comparing the two halves,
# restore the list to its original state by reversing the first half back. Not that the OJ or anyone else cares.
def isPalindrome(self, head):
    rev = None
    fast = head
    while fast and fast.next:
        fast = fast.next.next
        rev, rev.next, head = head, rev, head.next
    tail = head.next if fast else head
    isPali = True
    while rev:
        isPali = isPali and rev.val == tail.val
        head, head.next, rev = rev, head, rev.next
        tail = tail.next
    return isPali


290Word Pattern

给定一个模式和输入一个字符串,判断字符串是否符合模式

Examples:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. pattern = "abba", str = "dog dog dog dog" should return false.

我的代码:

class Solution:
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        plist = list(pattern)
        slist = re.split(r'\s',str)
        return len(plist) == len(slist) and len(set(zip(plist,slist))) == len(set(plist)) == len(set(slist))

大神的代码:

#From here:

def wordPattern(self, pattern, str):
    s = pattern
    t = str.split()
    return map(s.find, s) == map(t.index, t)
#Improved version also from there:

def wordPattern(self, pattern, str):
    f = lambda s: map({}.setdefault, s, range(len(s)))
    return f(pattern) == f(str.split())
#From here:

def wordPattern(self, pattern, str):
    s = pattern
    t = str.split()
    return len(set(zip(s, t))) == len(set(s)) == len(set(t)) and len(s) == len(t)

203Remove Linked List Elements

移除链表中的一个节点

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6

Return: 1 --> 2 --> 3 --> 4 --> 5

我的代码:

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

class Solution:
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        if not head:
            return head
        while head.val == val:
            head = head.next
            if not head:
                return head
        p = head
        c = p.next
        while c:
            if c.val == val:
                p.next = p.next.next
                c = p.next
            else:
                p,c = p.next,c.next
        return head
        

219Contains Duplicate II

给定一个整数和整数k的数组,找出数组中是否存在两个不同的索引i和j,使得nums [i] = nums [j],并且i和j之间的绝对差至多为k

我的代码:

class Solution:
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        dic = {}
        for i in range(len(nums)):
            if nums[i] in dic and abs(dic[nums[i]]-i) <= k:
                return True
            else:
                dic[nums[i]] = i
        return False

好一点的更简洁:

def containsNearbyDuplicate(self, nums, k):
    dic = {}
    for i, v in enumerate(nums):
        if v in dic and i - dic[v] <= k:
            return True
        dic[v] = i
    return False

507. Perfect Number

我们定义完美数是一个正整数,它等于除它自身之外的所有正因子的总和。 现在,给定一个整数n,编写一个函数,当它是一个完美数字时返回true,否则返回false。

我的代码:

class Solution:
    def checkPerfectNumber(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num <= 1:
            return False
        testnum = 2
        n = 1
        max_ = math.sqrt(num)
        while n <= num and testnum < max_:
            if num % testnum == 0:
                n += (testnum + num / testnum)
            testnum += 1
        if testnum == max_:
            n += max_
        return n == num

大神的代码:这个和perfect number的定义有关:https://en.wikipedia.org/wiki/Perfect_number#Even_perfect_numbers

def checkPerfectNumber(self, num):
    k = num.bit_length() / 2
    return num > 1 and num == (2 << k) - 1 << k


507. Perfect Number



507. Perfect Number


你可能感兴趣的:(Leetcode 算法题24)