leetcode(python)——169多數元素、200島嶼數量
阿新 • • 發佈:2021-01-15
技術標籤:LeetCode刷題
題號169
方法1:排序法
對陣列排序,重複的元素會排在一起,題目定義的多數元素為陣列中出現次數 大於 ⌊ n/2 ⌋ 的元素,對排序後的陣列求中間元素值,這個中間元素就是多數元素
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort()
left = 0
right =len(nums)-1
mid = (left+right)//2
n = nums[mid]
return n
方法2:雜湊表
統計陣列中每個元素出現的次數,遍歷key,找key的值大於 ⌊ n/2 ⌋ 的元素
class Solution:
def majorityElement(self, nums: List[int]) -> int:
dict={}
for num in nums:
if num not in dict:
dict[num]=0
dict[num]=dict.get(num)+1
mid = len(nums) //2
for key in dict.keys():
if dict[key]>mid:
return key
return -1
題號200
方法1:DFS
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if len(grid)==0:
return 0
row = len(grid)
col = len(grid[ 0])
count =0
for r in range (row):
for c in range (col):
if grid[r][c] == '1':
count+=1
self.DFS(grid,r,c)
return count
def DFS(self,grid,r,c):
if r<0 or c<0 or r>=len(grid) or c>=len(grid[0]) or grid[r][c]== '0':
return 0
grid[r][c]='0'
self.DFS(grid,r+1,c)
self.DFS(grid,r-1,c)
self.DFS(grid,r,c+1)
self.DFS(grid,r,c-1)