Saturday, April 13, 2019

LeetCode 307. Range Sum Query - Mutable

'''
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

The update(i, val) function modifies nums by updating the element at index i to val.
'''
#764ms, 15.8MB
class NumArray(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.nums = nums
     

    def update(self, i, val):
        """
        :type i: int
        :type val: int
        :rtype: None
        """
        self.nums[i] = val
     

    def sumRange(self, i, j):
        """
        :type i: int
        :type j: int
        :rtype: int
        """
        return sum(self.nums[i:j+1])


# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# obj.update(i,val)
# param_2 = obj.sumRange(i,j)

Tuesday, April 2, 2019

LeetCode 200. Number of Islands

'''
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

'''
class Solution:
    def findANDsink(self, i, j):
        if self.grid[i][j] == '1':
            self.grid[i][j] = '0'
            if not i == 0:
                self.findANDsink(i-1, j)
            if i < self.n-1:
                self.findANDsink(i+1, j)
            if not j == 0:
                self.findANDsink(i, j-1)
            if j < self.m-1:
                self.findANDsink(i, j+1)
       
   
    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid: return 0
       
        self.grid = grid
        self.n = len(grid)
        self.m = len(grid[0])
       
        i = 0
        j = 0
        self.count = 0
        for i in range(0, self.n):
            for j in range(0, self.m):
                if self.grid[i][j] == '1':
                    self.count += 1
                    self.findANDsink(i,j)
           
        return self.count