LeetCode Learning Notes --- HashTable

本文详细探讨了使用哈希表解决LeetCode中的3道问题:463 Island Perimeter,通过数学、迭代两种方法解析;136 Single Number利用XOR操作解决;953 Verifying Alien Dictionary的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

463 Island Perimeter

method#1: Math

Since the adjacent edge cannot be counted into perimeter, and each island cell has four edges, what we need to do is counting how many island cells(ones) and pairs of neighbor(two adjacent island called one pair of neighbor), and the answer is 4 * island_num - 2 * neighbor_num(subtracting 2 * neighbor_num because 4 * cell_num counts adjacent edges twice)

method#2: Iteration

The most intuitive way. Just iterate each cell, if it is an island, then check its surroundings(up, down, left, right), and there are two cases:
1 when the cell sits in boundary, its boundary edge should counted into perimeter
2 when the cell does not sit in boundary, only when its neighbor is water then that edge can be counted into perimeter

method#3: Another Iteration way

This method is kind of wired but excellent. The thought is similar to method#2, but more concise and elegant. Since each pair of neighbor cells (the edge between them) with different values is part of the perimeter, just count the differing pairs horizontally and vertically. When it comes to vertical iteration, one simple way is to transpose the matrix. In python, map(list,zip(*matrix)) can easily and effectively transpose a matrix.
Author: https://leetcode.com/problems/island-perimeter/discuss/95007/Short-Python

Code

import operator
class Solution:
    def islandPerimeter(self, grid: 'List[List[int]]') -> 'int':
        # math
        land, neighbor = 0, 0 
        for i in range(len(grid)):
            for j in range(len(grid[i])):
                if grid[i][j]==1:
                    land+=1
                    if i+1<len(grid) and grid[i+1][j]==1: #down neighbor
                        neighbor+=1
                    if j+1<len(grid[i]) and grid[i][j+1]==1: #down neighbor
                        neighbor+=1
        return land*4 - neighbor*2
    

    def islandPerimeter2(self, grid):
        #iteration
        m, n = len(grid), len(grid[0])
        if m==0:
            return 0
        ans = 0
        for i in range(m):
            for j in range(n):
                if grid[i][j]==1:
                    if i==0 or grid[i-1][j]==0:
                        ans+=1
                    if i==m-1 or grid[i+1][j]==0:
                        ans+=1
                    if j==0 or grid[i][j-1]==0:
                        ans+=1
                    if j==n-1 or grid[i][j+1]==0:
                        ans+=1
        return ans
    
    def islandPerimeter3(self, grid):
        # another iteration
        return sum(sum(map(operator.ne, [0]+row, row+[0])) for row in grid + list(map(list, zip(*grid))))

136 Single Number

https://leetcode.com/problems/single-number/
This question is pretty simple if no restrictions. But when it comes to requirement of linear running time complexity and no use of extra memory, it becomes kind of tricky. One approach meets the requirement is using XOR operation. Since:

x ^ 0 == x
x ^ x == 0
x ^ y ^ x == y

The code comes easily and clearly:

code

class Solution:
    def singleNumber(self, nums):
        x = 0
        for num in nums:
            x ^= num
        return x

953 Verifying Alien Dictionary

Approach

Actually, as long as the order is given, whether it is earth or alien does not matter. Then compare every two pair of words, from head to tail. (It works since if a<b, b<c, then a<c)

class Solution:
    def isAlienSorted(self, words, order):
        m = {c: i for i, c in enumerate(order)}
        for i in range(len(words)-1):
            if not self.compare(words[i], words[i+1], m):
                return False
        return True
    
    def compare(self, s1, s2, m):
        len1, len2 = len(s1), len(s2)
        for i in range(min(len1,len2)):
            if m[s1[i]] > m[s2[i]]:
                return False
            elif m[s1[i]] == m[s2[i]]:
                if len1>len2:
                    return False
            else:
                return True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值