1. 程式人生 > >leetcode簡單41-60(python)

leetcode簡單41-60(python)

171. Excel Sheet Column Number(e-41)

Given a column title as appear in an Excel sheet, return its corresponding column number.

class Solution(object):
    def titleToNumber(self, s):
        """
        :type s: str
        :rtype: int
        """
        letters = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "H": 8, "I": 9, "J": 10, "K": 11, "L": 12, "M": 13, "N": 14, "O": 15, "P": 16, "Q": 17, "R": 18, "S": 19, "T":20, "U": 21, "V": 22, "W": 23, "X": 24, "Y": 25, "Z": 26}
        s = s.upper()
        ret = 0
        b = 0
        for c in reversed(s):
            ret += letters[c] * 26**(b)
            b += 1
        return ret

172. Factorial Trailing Zeroes(e-42)

Given an integer n, return the number of trailing zeroes in n!.

class Solution(object):
    def trailingZeroes(self, n):
        """
        :type n: int
        :rtype: int
        """
        count, k=0, 0
        while n:
            k = n/5
            count+=k
            n=k
        return count
    

189. Rotate Array(e-43)

Given an array, rotate the array to the right by k steps, where k is non-negative.

class Solution(object):            #1
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        nums[:k],nums[k:] = nums[len(nums)-k:], nums[:len(nums)-k]



class Solution(object):    #2
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        old_nums=nums[:]
        for i in range(len(nums)):
            nums[(i+k)%len(nums)] = old_nums[i]

190. Reverse Bits-----------------沒看懂(e-44)

Reverse bits of a given 32 bits unsigned integer.

191. Number of 1 Bits(e-45)

Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        return bin(n).count("1")
        

198. House Robber(e-46)

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        now = last = 0
        for i in nums:
            last, now = now, max(i+last, now)
        return now

202. Happy Number(e-47)

Write an algorithm to determine if a number is "happy".

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        num_dict = {}

        while True:
            num_dict[n] = True
            sum = 0
            while(n>0):
                sum += (n%10)*(n%10)
                n /= 10
            if sum == 1:
                return True
            elif sum in num_dict:
                return False
            else:
                n = sum

 

203. Remove Linked List Elements(e-48)

Remove all elements from a linked list of integers that have value val.

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

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

204. Count Primes(e-49)-------------------------不懂

Count the number of prime numbers less than a non-negative number, n.

205. Isomorphic Strings(e-50)

Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        #return map(s.find, s) == map(t.find, t)
        return len(set(s)) == len(set(t)) == len(set(zip(s,t)))    

206. Reverse Linked List(e-51)--------

Reverse a singly linked list.

217. Contains Duplicate(e-52)

Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        nums.sort()
        for i in range(0, len(nums)-1):
            if nums[i] == nums[i+1]:
                return True
        return False
            

219. Contains Duplicate II(e-53)-------------

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

225. Implement Stack using Queues(e-54)

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

226. Invert Binary Tree(e-55)

Invert a binary tree.

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if not root:
            return 
        root.left, root.right=root.right, root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root

231. Power of Two(e-56)

Given an integer, write a function to determine if it is a power of two.

class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return n!=0 and (n&-n) == n

                
        
            
            

232. Implement Queue using Stacks(e-57)

Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.

234. Palindrome Linked List(e-58)

Given a singly linked list, determine if it is a palindrome.

235. Lowest Common Ancestor of a Binary Search Tree(e-59)

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given binary search tree:  root = [6,2,8,0,4,7,9,null,null,3,5]

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5
class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        a, b = sorted([p.val, q.val])
        while not a <= root.val <= b:
            if a > root.val:
                root = root.right
            else:
                root = root.left
        return root

237. Delete Node in a Linked List

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Given linked list -- head = [4,5,1,9], which looks like following:

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

class Solution(object):
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        node.val=node.next.val
        node.next=node.next.next