Leetcode 算法题02

来源:互联网 发布:windows桌面图标透明 编辑:程序博客网 时间:2024/05/16 17:17

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: 16Explanation: 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 = 4Output: [[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 = 4Output: [[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: 30Explanation: 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: 27Explanation: 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)
没看到更好的