)
EASY LEVEL:169.Majority ElementGiven an array of sizen, find the majority element. The majority element is the element that appearsmore than⌊ n/2 ⌋times.You may assume that the array is non-empty and the majority element always exist in the array.Example 1:Input:[3,2,3]Output:3Example 2:Input:[2,2,1,1,1,2,2]Output:2思路:这可以用字典也可以直接sort以后取中间的那个数,因为大于n/2次的数一定是排序以后出现在最中间。class Solution: def majorityElement(self, nums: List[int]) - int: from collections import Counter d = Counter(nums) return [k for (k,e) in d.items() if eint(len(nums)/2)][0] class Solution: def majorityElement(self, nums: List[int]) - int: return sorted(nums)[len(nums)//2]1108.Defanging an IP Address题目:Given a valid (IPv4) IPaddress, return a defanged version of that IP address. AdefangedIP addressreplaces every period"."with"[.]".Example 1:Input: address = "1.1.1.1" Output: "1[.]1[.]1[.]1"这道题其实就是把中间的'.'变成‘[.]’而已:class Solution: def defangIPaddr(self, address: str) - str: x = '[.]'.join(address.split(sep='.')) return(x)join相当于join一个string771.Jewels and StonesYou're given stringsJrepresenting the types of stones that are jewels, andSrepresenting the stones you have. Each character inSis a type of stone you have. You want to know how many of the stones you have are also jewels.The letters inJare guaranteed distinct, and all characters inJandSare letters. Letters are case sensitive, so"a"is considered a different type of stone from"A".Example 1:Input: J = "aA", S = "aAAbbbb" Output: 3此道题是看J中的字母在S中出现的次数的总和:1.在S中数一下每个出现字母的次数并分别求和; 2. 循环遍历J,把每个字母对应的加上。class Solution: def numJewelsInStones(self, J: str, S: str) - int: c = 0 for i in range(len(J)): c = c+ sum(map(J[i].count, S)) return cmap()函数的使用。938.Range Sum of BSTGiven therootnode of a binary search tree, return the sum of values of all nodes with value betweenLandR(inclusive).The binary search tree is guaranteed to have unique values.Example 1:Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 Output: 32这道题用到了递归的思想。画出这棵BST:假设二叉树顶点值为V,可以分成三种情况:1. VL: 那么顶点所有左子树都小于L,需要去右子树找到大于L并小于R的值;2. VR:那么顶点所有右子树都大于R,需要去左子树找到大于L并小于R的值;3.L=V=R: 这样左右子树都要找,因为顶点也包括在这个范围之内。代码:# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def rangeSumBST(self, root: TreeNode, L: int, R: int) - int: if not root: return 0 result = 0 if root.val R: #root = root.right result = result + self.rangeSumBST(root.left, L, R) elif root.val L: #root = root.left result = result + self.rangeSumBST(root.right, L, R) elif L = root.val = R: result = result + root.val result = result + self.rangeSumBST(root.left, L, R) result = result+ self.rangeSumBST(root.right, L, R) return result需要了解在什么时候使用递归的思想!709.To Lower CaseImplement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.Example 1:Input: "Hello" Output: "hello"非常简单的一道题,无需多说class Solution: def toLowerCase(self,