Leetcode 算法題02

344. Reverse String

輸入一個字符串,輸出反向

Example:
Given s = "hello", return "olleh".

我的代碼:怎麼還能有這種題

class Solution(object):
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        return s[::-1]

496. Next Greater Element I

給出一個數組,並給出一個子集,對子集中每個數字,找到原數組中的位置,向右找第一個比這個數字大的數,沒有則輸出-1

Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
    For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
    For number 1 in the first array, the next greater number for it in the second array is 3.
    For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

Example 2:

Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
    For number 2 in the first array, the next greater number for it in the second array is 3.
    For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
我的代碼:

class Solution(object):
    def nextGreaterElement(self, findNums, nums):
        """
        :type findNums: List[int]
        :type nums: List[int]
        :rtype: List[int]
        """
        ans = []
        for i in findNums:
            index = nums.index(i)
            for j in nums[index:]:
                if j > i:
                    ans.append(j)
                    break
                elif j == nums[-1]:
                    ans.append(-1)
        return ans
貌似沒看到比我好的,有一個將nums所有數字和其右邊第一個比其大的數字做成一個字典再進行索引,時間是一樣的

        d = {}
        st = []
        ans = []
        
        for x in nums:
            while len(st) and st[-1] < x:
                d[st.pop()] = x
            st.append(x)

        for x in findNums:
            ans.append(d.get(x, -1))
            
        return ans


463. Island Perimeter

計算河岸的邊長

Example:

[[0,1,0,0],
 [1,1,1,0],
 [0,1,0,0],
 [1,1,0,0]]

Answer: 16
Explanation: The perimeter is the 16 yellow stripes in the image below:

我的代碼:

class Solution(object):
    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        count = 0
        for i in range(len(grid)):
            for j in range(len(grid[i])):
                if grid[i][j] == 1:
                    count += 4
                    if i != 0 and grid[i-1][j] == 1:
                        count -= 1
                    if i != len(grid) - 1 and grid[i+1][j] == 1:
                        count -= 1
                    if j != 0 and grid[i][j-1] == 1:
                        count -= 1
                    if j != len(grid[i])-1 and grid[i][j+1] == 1:
                        count -= 1
        return count


大神的代碼:operator.ne(a, b)  等價 a!=b,將每行左右加個0並進行比較,上下的比較是通過將grid轉置加在grid後繼續計算左右,這個思路真的牛

def islandPerimeter(self, grid):
    return sum(sum(map(operator.ne, [0] + row, row + [0]))for row in grid + map(list, zip(*grid)))


566. Reshape the Matrix

實現matlab的reshape函數

Example 1:

Input: 
nums = 
[[1,2],
 [3,4]]
r = 1, c = 4
Output: 
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.

Example 2:

Input: 
nums = 
[[1,2],
 [3,4]]
r = 2, c = 4
Output: 
[[1,2],
 [3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
我的代碼
class Solution(object):
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        lists = []
        for m in nums:
            for n in m:
                lists.append(n)
        if len(lists) != r*c:
            return nums
        ans = []
        for i in range(r):
            ans.append([])
            for j in range(c):
                ans[i].append(lists.pop(0))       
        return ans
大神的代碼:大神給出了四個版本,跪拜。。除了import numpy的其他兩個都給上來了

def matrixReshape(self, nums, r, c):
    return nums if len(sum(nums, [])) != r * c else map(list, zip(*([iter(sum(nums, []))]*c)))

def matrixReshape(self, nums, r, c):
    flat = sum(nums, [])
    if len(flat) != r * c:
        return nums
    tuples = zip(*([iter(flat)] * c))
    return map(list, tuples)

def matrixReshape(self, nums, r, c):
    if r * c != len(nums) * len(nums[0]):
        return nums
    it = itertools.chain(*nums)
    return [list(itertools.islice(it, c)) for _ in xrange(r)]

412. Fizz Buzz

輸入一個正整數,輸出一個列表爲1~這個數,其中被3整除的,被5整除的,以及又被3又被5整除的用其他文字替換

Example:

n = 15,

Return:
[
    "1",
    "2",
    "Fizz",
    "4",
    "Buzz",
    "Fizz",
    "7",
    "8",
    "Fizz",
    "Buzz",
    "11",
    "Fizz",
    "13",
    "14",
    "FizzBuzz"
]
我的代碼:沒什麼難度,想到什麼就寫什麼了
class Solution(object):
    def fizzBuzz(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        ans = []
        for i in range (n):
            if (i+1) % 3 == 0 and (i+1) % 5 == 0:
                ans.append('FizzBuzz')
            elif (i+1) % 3 == 0:
                ans.append('Fizz')
            elif (i+1) % 5 == 0:
                ans.append('Buzz')
            else:
                ans.append(str(i+1))
        return ans
            
大神的代碼:我發現大神們都喜歡追求一行解題,不過python語言真的很像僞代碼,縮成一行還是很容易看懂

def fizzBuzz(self, n):
    return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n+1)]

682. Baseball Game

給出一個序列,按要求積分,數字則直接記有效分數,+記上兩個有效分數的和爲此次有效分數,D將上個有效分數乘2爲此次有效分數,C清除上一個有效分數

最後給出總有效分

Example 1:

Input: ["5","2","C","D","+"]
Output: 30
Explanation: 
Round 1: You could get 5 points. The sum is: 5.
Round 2: You could get 2 points. The sum is: 7.
Operation 1: The round 2's data was invalid. The sum is: 5.  
Round 3: You could get 10 points (the round 2's data has been removed). The sum is: 15.
Round 4: You could get 5 + 10 = 15 points. The sum is: 30.

Example 2:

Input: ["5","-2","4","C","D","9","+","+"]
Output: 27
Explanation: 
Round 1: You could get 5 points. The sum is: 5.
Round 2: You could get -2 points. The sum is: 3.
Round 3: You could get 4 points. The sum is: 7.
Operation 1: The round 3's data is invalid. The sum is: 3.  
Round 4: You could get -4 points (the round 3's data has been removed). The sum is: -1.
Round 5: You could get 9 points. The sum is: 8.
Round 6: You could get -4 + 9 = 5 points. The sum is 13.
Round 7: You could get 9 + 5 = 14 points. The sum is 27.
我的代碼:也是想到啥寫啥了

class Solution(object):
    def calPoints(self, ops):
        """
        :type ops: List[str]
        :rtype: int
        """
        anslist = []
        for i in ops:
            if i == 'C':
                anslist.pop()
            elif i == 'D':
                anslist.append(anslist[-1]*2)
            elif i == '+':
                anslist.append(anslist[-2]+anslist[-1])
            elif isinstance(int(i),int):
                anslist.append(int(i))
        return sum(anslist)
沒看到更好的


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章