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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: LeetCode是一个优秀的在线编程平台,提供了丰富的算法和数据结构题目供程序员练习。其中的简单题大多可以用Python语言编写,下面为您提供几个常见题目的Python版本答案。 1. 两数之和(Two Sum) 题目描述:给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 Python版本答案: class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: d = {} for i, x in enumerate(nums): if target - x in d: return [d[target - x], i] d[x] = i 2. 反转字符串(Reverse String) 题目描述:编写一个函数,其作用是将输入的字符串反转过来。 Python版本答案: class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ left, right = 0, len(s) - 1 while left < right: s[left], s[right] = s[right], s[left] left += 1 right -= 1 3. 回文数字(Palindrome Number) 题目描述:判断一个整数是否是回文数,例如:121是回文数,-121不是回文数。 Python版本答案: class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False if x == 0: return True str_x = str(x) left, right = 0, len(str_x) - 1 while left < right: if str_x[left] != str_x[right]: return False left += 1 right -= 1 return True 以上只是这几个简单题目的Python版本答案,实际上LeetCode上还有很多其他编程语言编写的优秀答案,需要程序员们自己去探索和实践。 ### 回答2: Leetcode是一个流行的在线编程题库,提供了许多关于算法和数据结构的题目,难度从简单到困难不等。Python是一种易学易用的编程语言,备受程序员欢迎。因此,许多程序员使用Python来解决Leetcode的编程问题。下面我将提供一些Python版本的Leetcode简单题的答案。 1. 两数之和 题目描述:给定一个整数数组和一个目标值,在数组中找到两个数之和等于目标值。 解题思路:使用哈希表来存储数组中每个元素的值和索引,然后遍历每个元素时,查找目标值减去当前元素的值是否在哈希表中,如果存在,返回两个值的索引。 Python代码: def twoSum(nums, target): hash_table = {} for i, num in enumerate(nums): complement = target - num if complement in hash_table: return hash_table[complement], i hash_table[num] = i nums = [2, 7, 11, 15] target = 9 print(twoSum(nums, target)) # Output: (0, 1) 2. 路径总和 题目描述:给定一棵二叉树和一个目标值,判断是否存在从根节点到叶节点的路径,使得路径上所有节点的值相加等于目标值。 解题思路:遍历二叉树的所有路径,判断路径上所有节点的值相加是否等于目标值。 Python代码: class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def hasPathSum(root, sum): if not root: return False if not root.left and not root.right and root.val == sum: return True return hasPathSum(root.left, sum - root.val) or hasPathSum(root.right, sum - root.val) root = TreeNode(5) root.left = TreeNode(4) root.right = TreeNode(8) root.left.left = TreeNode(11) root.left.left.left = TreeNode(7) root.left.left.right = TreeNode(2) root.right.left = TreeNode(13) root.right.right = TreeNode(4) root.right.right.right = TreeNode(1) sum = 22 print(hasPathSum(root, sum)) # Output: True 3. 最大子序和 题目描述:给定一个整数数组,找到一个具有最大和的子数组,返回该子数组的和。 解题思路:使用动态规划,定义状态dp[i]表示以第i个数结尾的最大子数组和,则状态转移方程为dp[i] = max(dp[i-1] + nums[i], nums[i])。 Python代码: def maxSubArray(nums): if not nums: return 0 n = len(nums) dp = [0] * n dp[0] = nums[0] for i in range(1, n): dp[i] = max(dp[i-1] + nums[i], nums[i]) return max(dp) nums = [-2,1,-3,4,-1,2,1,-5,4] print(maxSubArray(nums)) # Output: 6 总结:以上是三个Python版本的Leetcode简单题的答案,它们涉及到哈希表、二叉树、动态规划等算法和数据结构。这些题目既考验了程序员的基本功,又是训练算法思维的好工具。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值