高级编程作业 leetcode (三次作业三题合并) 五一节前 所有作业

第一题 : 283. 移动零
给定一个数组 nums, 编写一个函数将所有 0 移动到它的末尾,同时保持非零元素的相对顺序。

例如, 定义 nums = [0, 1, 0, 3, 12],调用函数之后, nums 应为 [1, 3, 12, 0, 0]。

注意事项:

必须在原数组上操作,不要为一个新数组分配额外空间。
尽量减少操作总数。

class Solution:
    def moveZeroes(self, nums):
        lens = 0
        for num in nums:
            lens = lens+1
        start = 0
        while start != lens:
             print(lens)
             print(start)
             i = start
             if nums[i] != 0:
                 start = start + 1
             else:
                 w = start
                 while w+1 < lens:
                     nums[w] = nums[w+1]
                     nums[w+1] = 0
                     w = w + 1
                 lens = lens-1

第二题: 20. 有效的括号
给定一个只包括 ‘(‘,’)’,’{‘,’}’,’[‘,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。


class Solution:
    def isValid(self, s):
        num = []
        i = 0
        while i < len(s):
           ## print(num)
            if len(num) == 0:
                if (s[i] == ']' or s[i] == ')' or s[i] == '}'):
                    return False
            else:
                if s[i] == ']':
                    if (num[len(num) - 1] != '['):
                        return False
                    else:
                        num.pop()

                if s[i] == ')':
                    if (num[len(num) - 1] != '('):
                        return False
                    else:
                        num.pop()

                if s[i] == '}':
                    if (num[len(num) - 1] != '{'):
                        return False
                    else:
                        num.pop()
            if (s[i] == '[' or s[i] == '(' or s[i] == '{'):
                num.append(s[i])
            i = i + 1
        if len(num) > 0:
            return False
        return True

第三题:268. 缺失数字
给出一个包含 0, 1, 2, …, n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。

class Solution:
    def missingNumber(self, nums):
        max = 0
        i = 0
        for num in nums:
            i = i + 1
        total = i * (i+1)/2
        for num in nums:
            total = total - num
        return int (total)

        """
        :type nums: List[int]
        :rtype: int
        """

猜你喜欢

转载自blog.csdn.net/riddlexyz/article/details/80156161