20191230-20200102总结(1)

LeetCode66. Plus One - Easy

LeetCode67. Add Binary - Easy

LeetCode69. Sqrt(x) - Easy 二分找

LeetCode70. Climbing Stairs - Easy dp

LeetCode71. Simplify Path - Medium

Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.

In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix

Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.

Example 1:

Input: "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.思路:注意‘/..hidden/‘这一类例子。用‘/‘split之后,用stack记录碰到的内容,且判断是否是‘.‘或者是‘..‘。 
class Solution:
    def simplifyPath(self, path: str) -> str:
        if not path or len(path) == 0:
            return " "
        res = ‘‘
        stack = []
        i = 0
        path = path.split(‘/‘)
        print(path)

        for i in range(len(path)):
            if not path[i] or path[i] == ‘.‘:
                continue
            elif path[i] == ‘..‘:
                if stack:
                    stack.pop()
                else:
                    continue
            else:
                stack.append(path[i])

        for i in range(len(stack)):
            res += ‘/‘+stack[i]
        if not res: res = ‘/‘
        return res

LeetCode72. Edit Distance - Hard

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

  1. Insert a character
  2. Delete a character
  3. Replace a character

Example 1:

Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace ‘h‘ with ‘r‘)
rorse -> rose (remove ‘r‘)
rose -> ros (remove ‘e‘)思路:和text regex一样的思路,用一个len(s1)+1  * len(s2) +1 的dp来记录状态。
class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        if not word1 or len(word1) == 0:
            return len(word2)
        if not word2 or len(word2) == 0:
            return len(word1)

        # the max will be len(word1)
        m = len(word1)
        n = len(word2)
        dp = [[0 for _ in range(n+1)] for _ in range(m+1)]

        temp = 1
        for i in range(1,m+1):
            dp[i][0] = temp
            temp += 1 

        dp[0] = [i for i in range(n+1)]

        for i in range(1, m+1):
            for j in range(1, n+1):
                if word1[i-1] == word2[j-1]:
                    dp[i][j] = dp[i-1][j-1]
                else:
                    dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
       # print(dp)
        return dp[-1][-1]
        

LeetCode73. Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.

Example 1:

Input:
[
  [1,1,1],
  [1,0,1],
  [1,1,1]
]
Output:
[
  [1,0,1],
  [0,0,0],
  [1,0,1]
]思路:用‘#’标记本来是1但是后来改为0的元素。
class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        if not matrix or len(matrix) == 0:
            return []
        rows = len(matrix)
        cols = len(matrix[0])

        for i in range(rows):
            for j in range(cols):
                if matrix[i][j] == 0:
                    row = i
                    col = j
                    for ii in range(rows):
                        if matrix[ii][col] != 0:
                            matrix[ii][col] = ‘#‘
                    for jj in range(cols):
                        if matrix[row][jj] != 0:
                            matrix[row][jj] = ‘#‘
        for i in range(rows):
            for j in range(cols):
                if matrix[i][j] == ‘#‘:
                    matrix[i][j] = 0 

LeetCode74.Search a 2D Matrix -Medium

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

Example 1:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
Output: true

Example 2:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
Output: false思路:先对每一行的l和r进行判断target是否在这一行里,如果不在的话,再用二分来找target。注意在这一行的时候,也需要对l和r来进行判断,以防出现这一行只有1个或者2个元素。!!注意[[]] 需要len(matrix[0])== 0来判断
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        if not matrix or len(matrix)==0 or len(matrix[0])== 0:
            return False 

        for i in range(len(matrix)):
            l = 0
            r = len(matrix[0])-1
            if matrix[i][l] > target or matrix[i][r] < target:
                print(‘!!‘)
                continue
            while l < r:
                mid  = l + (r-l) // 2 

                if matrix[i][mid] == target:
                    return True
                elif matrix[i][mid] > target:
                    r = mid
                else:
                    l = mid + 1
            if matrix[i][l] == target:
                return True
            if matrix[i][r] == target:
                return True 

        return False 

LeetCode75. Sort Colors - Medium

Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note: You are not supposed to use the library‘s sort function for this problem.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]思路:三个指针l, r, i. l指的是最后一个的0后面一位,i指的是1,r指的是第一个2开始的地方。1 while i<=r 循环2 如果i指到的元素是0,那么i和l指到的元素进行交换,且彼此都加13 如果i指到的元素是2,那么i和r指到的元素进行交换。r减1,注意的是i不能加1,因为我们不知道换来的元素是什么。4 如果i指到的元素是1,那么只需要i加1即可。
class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        if not nums or len(nums) == 0:
            return []

        l = 0
        r = len(nums)-1
        i  = 0
        while i <= r:
            if nums[i] == 0:
                nums[l], nums[i] = nums[i], nums[l]
                l += 1
                i += 1
            elif nums[i] == 2:
                nums[r], nums[i] = nums[i], nums[r]
                r -= 1
            else:
                i += 1 

LeetCode76. Minimum Window Substring - Hard

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

Example:

Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"

Note:

  • If there is no such window in S that covers all characters in T, return the empty string "".
  • If there is such a window, you are guaranteed that there will always be only one unique minimum window in S.

思路:two pointers + sliding window

步骤:

1 construct a counter for t and a missing for # of the characters for t

2 initialize a start, end and one of the pointers i to be zero

3 use enumerate to visit all the elements in the s. Be careful to set the index to start from 1.

1) for every element if the value in the counter for that element is greater than zero, which means t has this element, we will do missing -= 1

2) minus 1 of the value for every element in the counter

3) if the missing value is zero, it means we have already got all the characters in the t. We use i to do sliding window.

class Solution:
    def minWindow(self, s: str, t: str) -> str:
        if not s or len(s) == 0:
            return ""
        need = collections.Counter(t)
        missing = len(t)

        start = end = 0
        i = 0 

        for j, char in enumerate(s, 1):
            if need[char] > 0:
                missing -= 1
            need[char] -= 1

            if missing == 0:

                while i < j and need[s[i]] < 0:
                    need[s[i]] += 1
                    i += 1 

                need[s[i]] += 1
                missing += 1
                if end == 0 or j-i < end - start:
                    start, end = i, j
                i += 1
        return s[start:end]
         

原文地址:https://www.cnblogs.com/sky37/p/12144642.html

时间: 2024-10-14 11:17:34

20191230-20200102总结(1)的相关文章

2019-2020-1 20191230 《信息安全专业导论》第二周学习总结

教材学习内容总结: 只靠阅读就能习得新技能是拥有自学能力的终极目标.以前的观念“有些东西是书里面没有的”其实是书读的还不够多,只要书读的够多,所有问题几乎都能找到答案,但是读书不能只注重读书的数量,还要有选择的读书,放弃那些虚构的作品.知识是无国界的,不能因为语言不通就不去读原版书,版本不同的书给人的感受是不同的.互联网就是一本涉及广,内容新的一本书,通过它就可以了解到世界上的很多东西. 阅读要有策略,不能试图一下子就搞懂,了解一件事物的时候,首先要“脱盲”,先搞懂有关它的一些基本东西.学习一项

【2019-12-30】遇到好书应该多抄几遍

08:10 “一个人在才华被认可前,都要苦熬一段时间的,不是吗? ” ——欧.亨利 周末是我看书的好时光,在看书的过程,遇到好文字时我会摘抄写下来.所以,一本书的精华就是我记录的内容.这个周末我还在看<傅雷家书>,这是一本我不愿放下手的好书,但精华片段太多了,以至于我不得不频繁放下书本拿起手机记录.现在才看到一半,本周末的看书时间几乎有一半的时间都在抄写,我不知道算不算这本书的高潮了.遇到一本好书,让我完整抄一遍我都觉得是值得.就像我上半年做<软件方法>的笔记时候,我几乎抄写了整本

2019-12-30面试反思

面试公司: 一家中小型电商 面试中的问题: 思路不要太跳跃性, 不然容易尬. 引导的时候脑子需要快速运转该说什么. 自己熟的那块一定要准备充分答出百分之80以上. 排序算法, 选一个说: 建议快排, 归并, 面试前手写一下找找感觉. 挖坑桶排: 需要对难点做准备: 按照什么条件分桶? 空间利用率的优化等. 我下次打算挖坑下计排看看. Spark Core -> RDD -> 分类 -> 资源调度 -> Spark On Yarn 小文件处理: hdfs Hadoop Archive

2019年工作日

2019010220190103201901042019010720190108201901092019011020190111201901142019011520190116201901172019011820190121201901222019012320190124201901252019012820190129201901302019013120190201201902112019021220190213201902142019021520190218201902192019022020

[学习ES系列]-4.ElasticSearch基础交互-基础查询与高级查询

基础查询 POST http://127.0.0.1:9200/book/_search 1.简单查询 { "query":{ "match_all":{} } } 2.条件查询 { "query":{ "match":{ "title":"入门到精通" } }, "from":1, "size":5, "sort":{ &qu

Python的datetime模块使用

两个常量 MAXYEAR:9999 MINYEAR:1 五个类 datetime.datetime:日期时间类 datetime.date:日期类 datetime.time:时间类 datetime.timedelta:时间间隔,即两个时间点之间的长度 datetime.tzinfo:时区相关信息 datetime.datetime 参数 datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzi

【python数据分析实战】电影票房数据分析(一)数据采集

目录 1.获取url 2.开始采集 3.存入mysql 本文是爬虫及可视化的练习项目,目标是爬取猫眼票房的全部数据并做可视化分析. 1.获取url 我们先打开猫眼票房http://piaofang.maoyan.com/dashboard?date=2019-10-22 ,查看当日票房信息, 但是在通过xpath对该url进行解析时发现获取不到数据. 于是按F12打开Chrome DevTool,按照如下步骤抓包 再打开获取到的url:http://pf.maoyan.com/second-bo

MySql表分区(根据时间datetime)

timestamp 类型分区请移步=>MySql表分区(根据时间timestamp)环境: MySql8.0.18(5.6和5.7的未验证) 分区条件的字段类型是datetime完整的sql操作表分区的语句如下: -- 1.删除表 drop table t_test; -- =================================================================================== -- 2.创建一个表并对其分区,被创建分区的字段必须为主

Java日期时间API系列11-----Jdk8中java.time包中的新的日期时间API类,使用java8日期时间API重写农历LunarDate

通过Java日期时间API系列7-----Jdk8中java.time包中的新的日期时间API类的优点,java8具有很多优点,现在网上查到的农历转换工具类都是基于jdk7及以前的类写的,下面使用java新的日期时间API重写农历LunarDate. package com.xkzhangsan.time; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import ja

Python为什么要用抽象类(abc模块)?

原文: https://www.cnblogs.com/Black-rainbow/p/9582826.html 1.抽象类概念 抽象类是一个特殊的类,只能被继承,不能实例化 2.为什么要有抽象类 其实在未接触抽象类概念时,我们可以构造香蕉.苹果.梨之类的类,然后让它们继承水果这个基类,水果的基类包含一个eat函数. 但是你有没有想过,我们可以将香蕉.苹果.梨实例化,去吃香蕉.苹果.梨.但是我们却不能将水果实例化,因为我们无法吃到叫水果的这个东西. 所以抽象类中只能有抽象方法(没有实现功能),该