使用python刷Leetcode算法题(第一周)


明年六月份开始找工作,因此从这周开始刷题,希望记录一下刷题的过程,由于种种原因选择了python进行刷题,我会在每周的周日记录下本周在Leetcode中刷过的题,并附上代码以及心得,以作备忘。。。。。

Two Sum

  • 第1题

英文描述:Given an array of integers, return indices of the two numbers such that they add up to a specific

target.You may assume that each input would have exactly one solution, and you may not use the same

element twice.

例子:

    Given nums = [2, 7, 11, 15], target = 9,
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

题目描述: 找到一个数组中两个值得和等于固定值(target)返回这俩值得索引
解法:

def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if len(nums) <= 1:
            return False
        buff_dict = {}
        for i in range(len(nums)):
            if nums[i] in buff_dict:
                return [buff_dict[nums[i]], i]
            else:
                buff_dict[target - nums[i]] = i

解析: 利用一个字典,它的key是当前遍历的值与target相差多少,value是当前值得索引。在遍历数组时候,每当遍历到一个值时就查看与target的差值在不在字典中,如果在就返回当前索引,不在就把[差值,索引]记录。

Reverse Integer

  • 第2题

英文描述: Given a 32-bit signed integer, reverse digits of an integer.

note: Assume we are dealing with an environment which could only hold integers within the 

32-bit signed integer range. For the purpose of this problem, assume that your function

returns 0 when the reversed integer overflows.

例子:

Input: 123  Output:  321 
Input: -123   Output: -321
Input: 120  Output: 21

中文描述:返转一个正数,如果溢出返回0
解法:

def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x<0:
            return -self.reverse(-x)
        new_num = 0
        while x:
            new_num = x%10 + new_num*10
            x = x//10
        if new_num>2147483647:
            return 0
        return new_num

解析:将所给的数字利用余数法重构成新的正数

Palindrome Number

  • 第3题

英文描述:Determine whether an integer is a palindrome. Do this without extra space.

中文描述:不用额外空间判段一个数是不是回文
解法:

def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0:
            return False
        p = x
        q = 0
        while p >= 10:
            q *= 10
            q += p % 10
            p //= 10
        return q == int(x/10) and p == x%10

解析: 利用一个遍变量重构所给定的正数,重构方法就是获取正数最后一位然后慢慢增加位数,最终返回的值与当前值得(除去最后一位是否相等)

Roman to Integer

  • 第4题

英文描述: Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from

1 to 3999.

中文描述: 将罗马数字转成中文,其中假设罗马数字在1—3999中。

罗马数字转成整数描述:

罗马数字共有七个,即I(1),V(5),X(10),L(50),C(100),D(500),M(1000)。按照下面的规则可以表示任意正整数。
重复数次:一个罗马数字重复几次,就表示这个数的几倍。 
右加左减:在一个较大的罗马数字的右边记上一个较小的罗马数字,表示大数字加小数字。在一个较大的数字的左边记上一个较小的罗马数字,表示大数字减小数字。但是,左减不能跨越等级。比如,99不可以用IC表示,用XCIX表示。 
加线乘千:在一个罗马数字的上方加上一条横线或者在右下方写M,表示将这个数字乘以1000,即是原数的1000倍。同理,如果上方有两条横线,即是原数的1000000倍。 
单位限制:同样单位只能出现3次,如40不能表示为XXXX,而要表示为XL。

解法:

    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        roman2int = {"I": 1,"V" :5,"X": 10, "L": 50, "C": 100,"D": 500,"M":1000}
        s_list = list(s)
        l_list = []
        for i in s_list:
            l_list.append(roman2int.get(i))
        res = 0
        for j in range(len(l_list) - 1):
            if l_list[j]<l_list[j+1]:
                res -=l_list[j]
            else:
                res +=l_list[j]
        res += l_list[-1]
        return res

解析: 整体思想就是把原来的罗马字符串转成数字list,然后再根据罗马转整数规则转换

Valid Parentheses

  • 第5题

英文描述:Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is

valid.The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

中文描述:判断一个字符串标点是否合法
解法:

def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        s_f = list(s)
        if len(s_f) % 2 != 0:
            return False
        else:
            judge = ["()","{}","[]"]
            stack = []
            for l in s_f:
                try:
                    stop = stack.pop()
                except:
                    stack.append(l)
                    continue
                if stop + l in judge:
                    continue
                else:
                    stack.append(stop)
                    stack.append(l)
            if len(stack) != 0:
                return False
            else:
                return True

解析: 利用了python中list可以实现栈的思想。

Merge Two Sorted Lists

  • 第6题

英文描述: Merge two sorted linked lists and return it as a new list. The new list should be made by

splicing together the nodes of the first two lists.
例子:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

中文描述:有序合并两个listNode
解法:

def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1 or not l2:
            return l1 or l2
        if l1.val < l2.val:
            l1.next = self.mergeTwoLists(l1.next, l2)
            return l1
        else:
            l2.next = self.mergeTwoLists(l1, l2.next)
            return l2

解析: 采用了递归的思想,从两个listNode一个一个拿下来合并

Remove Duplicates from Sorted Array

  • 第7题

英文描述: Given a sorted array, remove the duplicates in-place such that each element appear only once

and return the new length.Do not allocate extra space for another array, you must do this by modifying

the input array in-place with O(1) extra memory.
例子:

Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the new length.

中文描述: 使用O(1)的空间复杂度去重
解法:

def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0:
            return 0
        length = 0
        for i in range(1,len(nums)):
            if nums[i] != nums[length]:
                length += 1
                nums[length] = nums[i]
        length += 1
        return length

解析: 利用两个索引,一个从0开始(最终要返回的),一个从1开始,遍历数组

Remove Element

  • 第8题

英文描述:Given an array and a value, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
例子:

Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.

中文描述:在数组中删除与给定值相等并且不改变原来的顺序、使用O(1)的空间复杂度
解法:

def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        for i in range(nums.count(val)):
            nums.remove(val)
        return len(nums)

解析:采用python的内建函数list.count() 和list.remove()

Implement strStr()

  • 第9题

英文描述: Implement strStr().Return the index of the first occurrence of needle in haystack, or -1 if needle

is not part of haystack.
例子:

Input: haystack = "hello", needle = "ll"
Output: 2
Input: haystack = "aaaaa", needle = "bba"
Output: -1

中文描述: 查找字符串中第一个出现目标字符的索引,没有,返回-1
解法:

def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        return haystack.find(needle)

解析: 采用python的内建函数str.find()

Search Insert Position

  • 第10题

英文描述:Given a sorted array and a target value, return the index if the target is found. If not, return the

index where it would be if it were inserted in order.You may assume no duplicates in the array.
例子:

Input: [1,3,5,6], 5
Output: 2
Input: [1,3,5,6], 2
Output: 1
Input: [1,3,5,6], 7
Output: 4
Input: [1,3,5,6], 0
Output: 0

中文描述:如果一个数在数组中,返回索引,否则返回插入位置的索引
解法:

def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums_copy = nums[:]
        if target < nums_copy[0]:
            nums_copy.insert(0, target)
            return 0
        for i in range(len(nums) - 1):
            if nums[i] == target:
                return i
            if nums[i + 1] > target and nums[i] < target:
                l = i
                nums_copy.insert(l + 1, target)
                return l + 1
        if target == nums_copy[-1]:
            return len(nums_copy) - 1
        else:
            nums_copy.append(target)
        return len(nums_copy) - 1

解析:直接遍历数组,考虑小于数组第一个,大于数组最后一个,在数组中,插入数组中

Maximum Subarray

  • 第11题

英文描述: Find the contiguous subarray within an array (containing at least one number) which has the

largest sum.
例子:

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

中文描述: 查找数组中和最大的子数组的和
解法:

def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0 
        curSum = maxSum = nums[0]
        for num in nums[1:]:
            curSum = max(num, curSum + num)
            maxSum = max(curSum, maxSum)
        return maxSum

解析: 采用两个变量记录数组的当前和与最大和,从第一个值开始遍历数组

Length of Last Word

  • 第12题

英文描述: Given a string s consists of upper/lower-case alphabets and empty space characters ’ ‘, return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.
例子:

Input: "Hello World"
Output: 5

解法:

def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        if s == "":
            return 0
        l = s.split(" ")
        for i in l[::-1]:
            if i == "":
                continue
            else:
                return len(i)
        return 0

解析: 直接逆序字符串,遍历字符串,直到出现一个空字符

Plus One

  • 第13题

英文描述:Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

中文描述: 给一个非负整数加1,返回它的list

解法:

def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        num = 0
        for i in range(len(digits)):
            num += digits[i] * pow(10, (len(digits)-1-i))
        return [int(i) for i in str(num+1)]

解析: 先把整数list收集成一个整数,在拆分

Add Binary

  • 第14题

英文描述: Given two binary strings, return their sum (also a binary string).

例子:

For example,
a = "11"
b = "1"
Return "100".

中文描述: 将两个二进制字符串相加,返回一个字符串
解法:

def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        if len(a)==0: return b
        if len(b)==0: return a
        if a[-1] == '1' and b[-1] == '1':
            return self.addBinary(self.addBinary(a[0:-1],b[0:-1]),'1')+'0'
        if a[-1] == '0' and b[-1] == '0':
            return self.addBinary(a[0:-1],b[0:-1])+'0'
        else:
            return self.addBinary(a[0:-1],b[0:-1])+'1'

解析:采用递归的思想

Sqrt(x)

  • 第15题

英文描述: Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

例子:

Input: 4
Output: 2

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.

解法:

def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        return math.floor(math.sqrt(x))

解析: 对x开方之后向下取整

Climbing Stairs

  • 第16题

英文描述: You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

例子:

Input: 2
Output:  2
Explanation:  There are two ways to climb to the top.

1. 1 step + 1 step
2. 2 steps

Input: 3
Output:  3
Explanation:  There are three ways to climb to the top.

1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

中文描述: 上楼,一次可以走1步或者2步,问到顶需要多少步
解法:

def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n == 1:
            return 1
        if n == 2:
            return 2
        a = 1
        b = 2
        s = 0
        for i in range(n-2):
            s = a + b
            a = b
            b = s
        return s

解析:类比 Fibonacci sequence

Remove Duplicates from Sorted List

  • 第17题

英文描述:Given a sorted linked list, delete all duplicates such that each element appear only once.

例子:

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

中文描述: 对一个listNode去重
解法:

def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        cur = head
        while cur:
            while cur.next and cur.next.val == cur.val:
                cur.next = cur.next.next
            cur = cur.next
        return head

解析:利用链表删除节点

Merge Sorted Array

  • 第18题

英文描述:Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

The number of elements initialized in nums1 and nums2 are m and n respectively.

中文描述:将两个有序数组合并成一个有序数组
解法:

def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: void Do not return anything, modify nums1 in-place instead.
        """
        while m > 0 and n > 0:
            if nums1[m-1] >= nums2[n-1]:
                nums1[m+n-1] = nums1[m-1]
                m -= 1
            else:
                nums1[m+n-1] = nums2[n-1]
                n -= 1
        if n >0:
            nums1[:n] = nums2[:n]

解析: 将两个数组的最大的值依次移动到最长数组(nums1)的最右侧

Same Tree

  • 第19题

英文描述:Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

例子:

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true
Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

中文描述:判断两个二叉树是否相等
解法:

def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        if p is None and q is None:
            return True
        if p is None or q is None:
            return False
        return (p.val == q.val) and self.isSameTree(p.left, q.left) and self.isSameTree(p.right,q.right)

解析:采用递归的思想

Symmetric Tree

  • 第20题

英文描述: Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

例子:

 For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
    1
   / \
  2   2
 / \ / \
3  4 4  3
But the following [1,2,2,null,3,null,3] is not:
    1
   / \
  2   2
   \   \
   3    3

中文描述:检查二叉树是否镜像对称

解法:

def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def isMirror(root, root1):
            if root == None and root1 == None:
                return True
            if root is None or root1 is None:
                return False
            return (root.val == root1.val) and isMirror(root.left, root1.right) and isMirror(root.right, root1.left)
        return isMirror(root,root)

解析:定义一个方法,判断两个两颗二叉树是否相等;然后判断一颗是不是对称就可以转化为以当前结点的左右子树是否相等

Maximum Depth of Binary Tree

  • 第21题

英文描述:Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the

farthest leaf node.

中文描述: 寻找一个二叉树的最长路径

解法:

def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0
        if root.left == None and root.right == None:
            return 1
        length = max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
        return length

解析: 采用递归的思想进行求解

Binary Tree Level Order Traversal II

  • 第22题

英文描述: Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left

to right, level by level from leaf to root).
例子:

For example:
Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
return its bottom-up level order traversal as:
[
  [15,7],
  [9,20],
  [3]
]

中文描述:从上到下,从左到右返回二叉树的节点
解法:

def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        stack = [(root,0)]
        res = []
        while stack:
            node, level = stack.pop()
            if node:
                if len(res) < level +1:
                    res.insert(0,[])
                res[-(level + 1)].append(node.val)
                stack.append((node.right, level + 1))
                stack.append((node.left, level + 1))
        return res

解析: 利用python的list实现的栈的结构求解,按照层次遍历的方法

Convert Sorted Array to Binary Search Tree

  • 第23题

英文描述: Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two

subtrees of every node never differ by more than 1.

例子:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

中文描述: 将一个有序数组转成平衡二叉树

解法:

def sortedArrayToBST(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        if not nums:
            return None

        mid = math.floor(len(nums) / 2)

        root = TreeNode(nums[mid])
        root.left = self.sortedArrayToBST(nums[:mid])
        root.right = self.sortedArrayToBST(nums[mid+1:])
        return root

解析: 采用递归的思想,一个有序数组转成二叉平衡树,先获取到中间的值,当作根,然后比它小的是左子树,比它大的为右子树,做循环

Balanced Binary Tree

  • 第24题

英文描述: Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two

subtrees of every node never differ by more than 1.

中文描述:判断一个二叉树是不是平衡二叉树

解法:

def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def getDepth(root):
            if root == None:
                return 0
            if root.left == None and root.right == None:
                return 1
            l = getDepth(root.left)
            r = getDepth(root.right)
            if l == -99 or r == -99 or max(l,r) - min(l,r) > 1:
                return -99
            return max(l, r) + 1
        if root == None:
            return True 
        return getDepth(root) != -99

解析:利用平衡二叉树的左子树和右子树的差的绝对值不大于1求解

Minimum Depth of Binary Tree

  • 第25题

英文描述:Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

中文描述:找出二叉树中最短路径

解法:

def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """ 
        if root == None:
            return 0
        l = self.minDepth(root.left)
        r = self.minDepth(root.right)
        if l == 0 or r == 0:
            return l +r + 1
        else:
            return min(l,r) + 1

解析: 利用递归思想求解,主要特殊考虑单枝树

Path Sum

  • 第26题

英文描述: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up

all the values along the path equals the given sum.

例子:

For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

中文描述:判断二叉树中是否有路径的和等于给定的值

解法:

def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if not root:
            return False
        if not root.left and not root.right and root.val == sum:
            return True
        sum -= root.val
        return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)

解析: 利用先序遍历的递归思想,每次遍历一个值都减去当前值

不要嫌弃一周刷的慢,实在是事多,我一般只有晚上才会刷题,等开题之后闲下来了就主刷题啦,希望最后能找到一个适合自己的工作,哈哈哈

  • 10
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值