Leetcode刷題——Day2

695. Max Area of Island

Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

Example 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.

思路:

這一題我自己想了好久沒想出來,參考了一下大神的答案,現在大致說一下:
其實就是求大矩陣下有幾個連着的1,就是求連着的1的最大數目(1和1之間不能用0隔開,否則就不算了)
遍歷矩陣中的每一個點,注意這個矩陣是會變化的,原來是1訪問一次之後就會變成0,也就是會實時更新。然後把這個爲1的點放到stack列表中,然後開始遍歷這個點周圍的四個點的值,如果周圍某一個點爲1,就把這個新點的座標也放到stack種存起來,但是要注意更新這些爲1的點的值,也就是存到stack之後就得置爲0了,一次次的訪問stack中的值,其實也就是上一次存的值爲1的那些點的座標(這裏每訪問一次stack 就會刪掉一個值)再遍歷當前點的周圍四個點,如果發現有新的1值點,再存到stack中去,知道stack爲空,,接下來就可以重新開始檢索矩陣中的元素,找到該元素爲起始點構成的新面積值,然後更新max的值(存的是當前所構成的最大面積值)

class Solution:
    def maxAreaOfIsland(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        Max=0
        m,n=len(grid),len(grid[0])
        for i in range(m):
            for j in range(n):
                if grid[i][j]:
                    area=0  #每次查找一個點 都初始化當前點的area=0
                    stack=[(i,j)]  #存放的是當前點周圍爲1的點的個數
                    grid[i][j]=0
                    while stack:
                        cur_i,cur_j=stack.pop()
                        area+=1
                        if cur_i-1>=0 and grid[cur_i-1][cur_j]:
                            stack.append((cur_i-1,cur_j))
                            grid[cur_i-1][cur_j]=0
                        if cur_i+1<m and grid[cur_i+1][cur_j]:
                            stack.append((cur_i+1,cur_j))
                            grid[cur_i+1][cur_j]=0
                        if cur_j-1>=0 and grid[cur_i][cur_j-1]:
                            stack.append((cur_i,cur_j-1))
                            grid[cur_i][cur_j-1]=0
                        if cur_j+1<n and grid[cur_i][cur_j+1]:
                            stack.append((cur_i,cur_j+1))
                            grid[cur_i][cur_j+1]=0
                        print(area)
                    Max=max(area,Max)

        return Max

283. Move Zeroes

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

思路:

這一題真的不是用來充數的嘛,,,

class Solution:
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        n=0
        for i in nums:
            if i==0:
                nums.remove(0)
                nums.append(0)

448. Find All Numbers Disappeared in an Array

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

思路:

這一題思路應該很簡單,可是寫出來以後發現超時了竟然,然後參考了這篇博客提到的difference函數 可以用來求兩個集合的差集,這樣運行就不會超時啦(博客還講了求兩個集合的並集用的intersection()函數)

class Solution:
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        n=len(nums)
        L=[]
        for i in range(1,n+1):
            L.append(i)
        return list(set(L).difference(set(nums)))

下面這個是我第一次寫的超時的,,不過簡單的數據也是可以的,嘻嘻

def findDisappearedNumbers(nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        L=[]
        n=len(nums)
        for i in range(1,n+1):
            if i not in nums:
                L.append(i)
        return L

830. Positions of Large Groups

In a string S of lowercase letters, these letters form consecutive groups of the same character.

For example, a string like S = “abbxxxxzyy” has the groups “a”, “bb”, “xxxx”, “z” and “yy”.

Call a group large if it has 3 or more characters. We would like the starting and ending positions of every large group.

The final answer should be in lexicographic order.

Example 1:

Input: “abbxxxxzzy”
Output: [[3,6]]
Explanation: “xxxx” is the single large group with starting 3 and ending positions 6.

思路:

這一題其實挺簡單,就是從重複的那個字符串開始計數,從第一個字符遍歷到倒數第二個字符,查看下一個字符和當前字符是否一樣,一樣則將長度累加,否則就重新開始計數,但是在清空之前需要判斷重複的字符串長度是不是滿足要求,決定是否存到列表中,後來運行當出現的字符串是‘aaa’這種開始到最後都相同,才發現邏輯上有點問題,就是需要在滿足第一個條件累加計數時判斷是不是到末尾了,這種情況也應該返回,但是不屬於第二種情況也就是下一個字符不等於上一個字符的情況,因爲到末尾他沒有下一個啦~~
我也不知道爲什麼又想的如此複雜。。

class Solution:
    def largeGroupPositions(self, S):
        """
        :type S: str
        :rtype: List[List[int]]
        """
        L=[]
        n,length=len(S),1
        for i in range(n-1):
            if S[i+1]==S[i]:
                length+=1
                if i==n-2:
                    if length>=3:  
                        L.append((i-length+2,i+1))
                        return L
            else:
                if length>=3:
                    L.append((i-length+1,i))
                length=1
        return L

嗯,下面的是我看的討論區別人的代碼,覺得又被秒了。。。

def largeGroupPositions(self, S):
        i, j, N = 0, 0, len(S)
        res = []
        while j < N:
            while j < N and S[j] == S[i]: j += 1
            if j - i >= 3: res.append((i, j - 1))
            i = j
        return res
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章