leetcodeday74 –搜索二维矩阵

编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

  • 每行中的整数从左到右按升序排列。
  • 每行的第一个整数大于前一行的最后一个整数。

示例 1:

输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
输出:true
# [74] 搜索二维矩阵
#

# @lc code=start
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        def twoserch(nums,i,j,target):
            # i=0
            # j=len(nums)-1
            if nums[0]==target:
                return True
            mid=(i+j)//2
            while i<j-1:
                mid=(i+j)//2
                if nums[mid]==target:
                    return True
                elif nums[mid]<target:
                    i=mid
                else:
                    j=mid
            return False


        j=-1
        for i in range(len(matrix)):
            if target<matrix[i][-1]:
                j=i
                break
            elif target==matrix[i][-1]:
                return True
        if j == -1:
            return False
        else:
            lens=len(matrix[j])
            return twoserch(matrix[j],0,lens-1,target)
# @lc code=end

leetcodeday73–矩阵置零

给定一个 m x n 的矩阵,如果一个元素为 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法

示例 1:

输入:matrix = [[1,1,1],[1,0,1],[1,1,1]]
输出:[[1,0,1],[0,0,0],[1,0,1]]

代码:

# @lc app=leetcode.cn id=73 lang=python3
#
# [73] 矩阵置零
#

# @lc code=start
class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        m=len(matrix)
        n=len(matrix[0])
        res=list()
        for i in range(m):
            for j in range(n):
                if matrix[i][j]==0:
                    res.append([i,j])
        for l in res:
            matrix[l[0]]=[0]*n
            for  x in matrix:
                x[l[1]]=0 

leetcodeday68 –文本左右对齐

给定一个单词数组和一个长度 maxWidth,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本。

你应该使用“贪心算法”来放置给定的单词;也就是说,尽可能多地往每行中放置单词。必要时可用空格 ' ' 填充,使得每行恰好有 maxWidth 个字符。

要求尽可能均匀分配单词间的空格数量。如果某一行单词间的空格不能均匀分配,则左侧放置的空格数要多于右侧的空格数。

文本的最后一行应为左对齐,且单词之间不插入额外的空格。

说明:

  • 单词是指由非空格字符组成的字符序列。
  • 每个单词的长度大于 0,小于等于 maxWidth
  • 输入单词数组 words 至少包含一个单词。

示例:

输入:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
输出:
[
   "This    is    an",
   "example  of text",
   "justification.  "
]

示例 2:

输入:
words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
输出:
[
  "What   must   be",
  "acknowledgment  ",
  "shall be        "
]
解释: 注意最后一行的格式应为 "shall be    " 而不是 "shall     be",
     因为最后一行应为左对齐,而不是左右两端对齐。       
     第二行同样为左对齐,这是因为这行只包含一个单词。

示例 3:

输入:
words = ["Science","is","what","we","understand","well","enough","to","explain",
         "to","a","computer.","Art","is","everything","else","we","do"]
maxWidth = 20
输出:
[
  "Science  is  what we",
  "understand      well",
  "enough to explain to",
  "a  computer.  Art is",
  "everything  else  we",
  "do                  "
]

code:

# [68] 文本左右对齐
#

# @lc code=start
class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        lens=len(words)
        rev=list()
        nowlens=0
        start=0
        i=0
        while i<lens:
            wordlen=len(words[i])
            nowlens=nowlens+wordlen
            #print(i,nowlens)
            if nowlens<maxWidth:
                nowlens+=1
                i=i+1
                #print(i)
                #print(nowlens)
            elif nowlens>maxWidth:
                nowlens=nowlens-wordlen-1
                
                reslens=maxWidth-nowlens
                m=(i-1-start)
                if m==0:
                    mid=""
                    mid=mid+words[start]+(maxWidth-len(words[start]))*" "
                    rev.append(mid)
                #print(reslens,reslens//(i-1-start),reslens/(i-1-start))
                elif reslens//(i-1-start)==reslens/(i-1-start):
                    mid=""
                    x=reslens//(i-1-start)+1
                    for j in range(start,i-1):
                        mid=mid+words[j]+x*" "
                    mid=mid+words[i-1]
                    rev.append(mid)
                else:
                    other=reslens%(i-1-start)
                    mid=""
                    x=reslens//(i-1-start)+1
                    print(x,other)
                    for j in range(start,i-1):
                        if other>0:
                            mid=mid+words[j]+x*" "+" "
                            other-=1
                        else:
                            mid=mid+words[j]+x*" "
                    mid=mid+words[i-1]
                    rev.append(mid)
                nowlens=0
                start=i
            elif nowlens==maxWidth:
                mid=""
                for j in range(start,i):
                    mid=mid+words[j]+" "
                mid=mid+words[i]
                rev.append(mid)
                start=i+1
                nowlens=0
                i=i+1
        if start<lens:
            mid=""
            for j in range(start,lens):
                mid=mid+words[j]+" "
            mid=mid[:-1]
            other=maxWidth-len(mid)
            mid=mid+other*" "
            rev.append(mid)
        return rev    
                
             
# @lc code=end

leetodeday77 –组合

给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。

你可以按 任何顺序 返回答案。

示例 1:

输入:n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

示例 2:

输入:n = 1, k = 1
输出:[[1]]

递归实现:

易错点: re=copy.deepcopy(rev) 需要深拷贝

# @lc app=leetcode.cn id=77 lang=python3
#
# [77] 组合
#
#递归:
# @lc code=start
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        rev=list()
        res=list()
        import copy
        def f(n,k):
            if k==0:
                re=copy.deepcopy(rev)
                res.append(re)
                return 

            else:
              for i in range(n,k-1,-1):
                  rev.append(i)
                  f(i-1,k-1)
                  rev.pop()
        f(n,k)
        return res

leetcodeday83 –删除排序链表中的重复元素

存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。

返回同样按升序排列的结果链表。

示例 1:

输入:head = [1,1,2]
输出:[1,2]

示例 2:

输入:head = [1,1,2,3,3]
输出:[1,2,3]

提示:

  • 链表中节点数目在范围 [0, 300] 内
  • -100 <= Node.val <= 100
  • 题目数据保证链表已经按升序排列
# @lc app=leetcode.cn id=83 lang=python3
#
# [83] 删除排序链表中的重复元素
#

# @lc code=start
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        head0=head
        end=head
        while end!=None:
            if end.next!=None and head.val==end.next.val:
                end=end.next
            elif end.next!=None and head.val!=end.next.val:
                head.next=end.next
                head=head.next
                end=head
            elif end.next==None and head.val==end.val:
                head.next=None
                end=end.next
            else:
                return head0

        return head0
# @lc code=end

leetcodeday30 –串联所有单词的字串

给定一个字符串 s 和一些 长度相同 的单词 words 。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。

注意子串要与 words 中的单词完全匹配,中间不能有其他字符 ,但不需要考虑 words 中单词串联的顺序。

示例 1:

输入:s = "barfoothefoobarman", words = ["foo","bar"]
输出:[0,9]
解释:
从索引 0 和 9 开始的子串分别是 "barfoo" 和 "foobar" 。
输出的顺序不重要, [9,0] 也是有效答案。

示例 2:

输入:s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
输出:[]

示例 3:

输入:s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
输出:[6,9,12]

提示:

  • 1 <= s.length <= 104
  • s 由小写英文字母组成
  • 1 <= words.length <= 5000
  • 1 <= words[i].length <= 30
  • words[i] 由小写英文字母组成

挨个匹配:

# @lc app=leetcode.cn id=30 lang=python3
#
# [30] 串联所有单词的子串
#

# @lc code=start
class Solution:
    def findSubstring(self, s: str, words: List[str]) -> List[int]:
        import copy
        ls=len(s)
        lw=len(words)
        wordlen=len(words[0])
        dicts=dict()
        res=[]
        for i in range(lw):
            if words[i] in  dicts:
                dicts[words[i]]=dicts[words[i]]+1
            else:
                dicts[words[i]]=1
        for i in range(ls-wordlen*lw+1):
            new=copy.copy(dicts)
            rev=1
            for j in range(i,i+wordlen*lw,wordlen):
                if s[j:j+wordlen] in new and new[s[j:j+wordlen]]!=0:
                    new[s[j:j+wordlen]]-=1
                else:
                    rev=0
                    break
            if rev==1:
                res.append(i)
        return res




# @lc code=end

leetcodeday25 — K 个一组翻转链表

给你一个链表,每 个节点一组进行翻转,请你返回翻转后的链表。

是一个正整数,它的值小于或等于链表的长度。

如果节点总数不是 的整数倍,那么请将最后剩余的节点保持原有顺序。

示例 1:

输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]

法 一:只交换值

# [25] K 个一组翻转链表
#
#法1 :只交换值
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next


class Solution:
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        head1=head
        fhead= ListNode(0,head)
        head2=fhead
        end=0
        while head1!= None:
            nums=list()
            for i in range(k):
                head2=head2.next
                if head2==None:
                    end=1
                    break 
                #print(head2.val)   
                nums.append(head2.val)
            if end==0:
                for i in range(k):
                    head1.val=nums[k-1-i]
                    head1=head1.next
            else:
                for i in range(len(nums)):
                    head1.val=nums[i]
                    head1=head1.next
        return  fhead.next   
# @lc code=end

进阶:

  • 你可以设计一个只使用常数额外空间的算法来解决此问题吗?
  • 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。

法二:节点交换(不只是单纯改变值) 代做。。

leetcodeday24 –两两交换链表中的节点

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

示例 1:

输入:head = [1,2,3,4]
输出:[2,1,4,3]

代码:

# [24] 两两交换链表中的节点
#

# @lc code=start
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        # head0 = ListNode(0,head)
        if head==None or head.next==None:
            return head
        head0=head
        headr=head.next

        while head0!=None:
            head1=head0
            head2=head0.next
            head3=head2.next
            #print(head3.val)
            head2.next=head1
            if head3==None:    
                head1.next=None
                #print("is 1")
                return headr
            if head3.next==None:
                head1.next=head3
                #print("is 2")

                return headr
            else:
                head1.next=head3.next
                #print(head3.val)
                #print("is 0")

                head0=head3
                #print(head0.val)
        return headr

leetcodeday69 –求sqrt

给你一个非负整数 x ,计算并返回 x 的 算术平方根 。

由于返回类型是整数,结果只保留 整数部分 ,小数部分将被 舍去 。

注意:不允许使用任何内置指数函数和算符,例如 pow(x, 0.5) 或者 x ** 0.5 。

示例 1:

输入:x = 4
输出:2

示例 2:

输入:x = 8
输出:2
解释:8 的算术平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。

二分法求解:

# @lc app=leetcode.cn id=69 lang=python3
#
# [69] Sqrt(x)
#
#二分法
# @lc code=start
class Solution:
    def mySqrt( self,x: int) -> int:
        mid=x//2
        end=x
        start=0
        if x==1:
            return 1
        while end>start+1:
            l=mid**2            
            if  l==x:
                return mid
            if  l<x :
                start=mid
                mid = (mid+end)//2
                continue
            if  l>x:
                end=mid
                mid = (mid)//2
                continue
        return start

leetcodeday70 –爬楼梯

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

示例 1:

输入:n = 2
输出:2
解释:有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶

示例 2:

输入:n = 3
输出:3
解释:有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶 + 1 阶

动态规划 or 递归

# @lc app=leetcode.cn id=70 lang=python3
#
# [70] 爬楼梯
#

# @lc code=start
class Solution:
    def climbStairs(self, n: int) -> int:
        dp=[0 for i in range(n)]
        
        for i in range(n):
            if i == 0:
                dp[0]=1
                continue
            if i == 1:
                dp[1]=2
                continue
            dp[i]=dp[i-1]+dp[i-2]
        return dp[n-1]