最近开始刷lintcode,记录下自己的答案,数字即为lintcode题目号,语言为python3,坚持日拱一卒吧。。。

(一). 回文字符窜问题(Palindrome problem)

627. Longest Palindrome

给出一个包含大小写字母的字符串。求出由这些字母构成的最长的回文串的长度是多少。

数据是大小写敏感的,也就是说,"Aa" 并不会被认为是一个回文串

  1. 输入 : s = "abccccdd"
  2. 输出 : 7
  3. 说明 : 一种可以构建出来的最长回文串方案是 "dccaccd"
  1. #coding:utf-
  2.  
  3. class Solution:
  4. """
  5. @param s: a string which consists of lowercase or uppercase letters
  6. @return: the length of the longest palindromes that can be built
  7. """
  8. def longestPalindrome(self, s):
  9. # write your code here
  10. char_set=set()
  11. for c in s:
  12. if c in char_set:
  13. char_set.remove(c) #出现偶数次的字母去除掉,留下出现奇数次
  14. else:
  15. char_set.add(c)
  16. single_count = len(char_set)
  17. if single_count>:
  18. single_count = single_count- #留一个单字母在回文正中间
  19. return len(s)-single_count
  20. if __name__=="__main__":
  21. s = Solution()
  22. print(s.longestPalindrome("abccccdd"))

627

200. Longest Palindromic Substring

Description

给出一个字符串(假设长度最长为1000),求出它的最长回文子串,你可以假定只有一个满足条件的最长回文串。

Example

样例 1:

  1. 输入:"abcdzdcab"
  2. 输出:"cdzdc"

样例 2:

  1. 输入:"aba"
  2. 输出:"aba"
  1. #coding:utf-
  2.  
  3. class Solution:
  4.  
  5. def longestPalindrome(self, s):
  6. # write your code here
  7. length = len(s)
  8. sub="" if length> else s
  9. m =
  10. for i in range(length-):
  11. len1,sub1 = expandAroundCenter(s,m,i,i)
  12. len2,sub2 = expandAroundCenter(s,m,i,i+)
  13. if len1>m:
  14. m = len1
  15. sub = sub1
  16. if len2>m:
  17. m = len2
  18. sub = sub2
  19. return sub
  20.  
  21. def expandAroundCenter(s,m,i,j):
  22. sub=""
  23. while i>= and j<=len(s)-:
  24. if s[i]==s[j]:
  25. if j-i+>m:
  26. m = j-i+
  27. sub = s[i:j+]
  28. i=i-
  29. j=j+
  30. else:
  31. break
  32. return m,sub
  33.  
  34. if __name__=="__main__":
  35. s = Solution()
  36. print(s.longestPalindrome("abcdzdcab"))
  37. print(s.longestPalindrome("aba"))
  38. print(s.longestPalindrome("a"))
  39. print(s.longestPalindrome("ccc"))
  40. print(s.longestPalindrome("cc"))
  41. print(s.longestPalindrome("cccc"))

(二).  二分搜索法和log(n)算法(Binary Search & Log(n) Algorithm)

458. Last Position of Target

  给一个升序数组,找到 target 最后一次出现的位置,如果没出现过返回 -1

  样例 :

  1.   输入:nums = [1,2,2,4,5,5], target = 2
  2.   输出:2
  1.   输入:nums = [1,2,2,4,5,5], target = 6
  2.   输出:-1
  1. #coding:utf-
  2.  
  3. class Solution:
  4. #获取最右边的
  5. def lastPosition(self, nums, target):
  6. start =
  7. end = len(nums)-
  8. index = -
  9. while start<=end:
  10. mid = (start+end)//
  11. if nums[mid]<=target:
  12. start = mid+
  13. elif nums[mid]>target:
  14. end = mid-
  15.  
  16. if start> and nums[start-]==target:
  17. index = start-
  18. return index
  19. #获取最左边的
  20. def firstPosition(self, nums, target):
  21. start =
  22. end = len(nums)-
  23. index = -
  24. while start<=end:
  25. mid = (start+end)//
  26. if nums[mid]<target:
  27. start = mid+
  28. elif nums[mid]>=target:
  29. end = mid-
  30.  
  31. if end<len(nums)- and nums[end+]==target:
  32. index = end+
  33. return index
  34.  
  35. if __name__=="__main__":
  36. s = Solution()
  37. print(s.lastPosition(nums = [], target = ))
  38. print(s.lastPosition(nums = [,,,,,], target = ))
  39. print(s.lastPosition(nums = [,,,,,], target = ))
  40. print(s.lastPosition(nums = [,,,,,], target = ))
  41.  
  42. print(s.firstPosition(nums = [,,,,,], target = ))
  43. print(s.firstPosition(nums = [,,,,,], target = ))
  44. print(s.firstPosition(nums = [,,,,,], target = ))

458

585. Maximum Number in Mountain Sequence

  给 n 个整数的山脉数组,即先增后减的序列,找到山顶(最大值)

Example

例1:

  1. 输入: nums = [1, 2, 4, 8, 6, 3]
  2. 输出: 8

例2:

  1. 输入: nums = [10, 9, 8, 7],
  2. 输出: 10
  1. #coding:utf-
  2.  
  3. class Solution:
  4.  
  5. def mountainSequence(self, nums):
  6. # write your code here
  7. if len(nums)==:
  8. return nums[]
  9. for i in range(len(nums)-):
  10. if nums[i+]<nums[i]:
  11. return nums[i]

585

460. Find K Closest Elements

Description

  给一个目标数 target, 一个非负整数 k, 一个按照升序排列的数组 A。在A中找与target最接近的k个整数。返回这k个数并按照与target的接近程度从小到大排序,如果接近程度相当,那么小的数排在前面。

  1. k是一个非负整数,并且总是小于已排序数组的长度。
  2. 给定数组的长度是正整数, 不会超过 10^44​​
  3. 数组中元素的绝对值不会超过 10^44​​

Example

样例 1:

  1. 输入: A = [1, 2, 3], target = 2, k = 3
  2. 输出: [2, 1, 3]

样例 2:

  1. 输入: A = [1, 4, 6, 8], target = 3, k = 3
  2. 输出: [4, 1, 6]
  1. class Solution:
  2. """
  3. @param A: an integer array
  4. @param target: An integer
  5. @param k: An integer
  6. @return: an integer array
  7. """
  8. def kClosestNumbers(self, A, target, k):
  9. # write your code here
  10. sub=
  11. nearest=-
  12. start =
  13. end = len(A)-
  14. while start<=end:
  15. mid = (start+end)//
  16. temp = abs(A[mid]-target)
  17. if temp<sub:
  18. sub = temp
  19. nearest = mid
  20. if A[mid]>target:
  21. end = mid-
  22. elif A[mid]<target:
  23. start = mid+
  24. elif A[mid]==target:
  25. break
  26. out=[]
  27. if nearest!=- and k>:
  28. out.append(A[nearest])
  29. i=
  30. left,right=nearest-,nearest+
  31. while left>= and right<=len(A)- and i<k:
  32. if abs(A[left]-target)<=abs(A[right]-target):
  33. out.append(A[left])
  34. left = left-
  35. else:
  36. out.append(A[right])
  37. right = right+
  38. i = i+
  39.  
  40. if i<k and left<:
  41. out.extend(A[right:right+k-i])
  42. if i<k and right>len(A)-:
  43. out.extend(A[left:left-(k-i):-])
  44. return out
  45. if __name__=="__main__":
  46. s = Solution()
  47. print(s.kClosestNumbers( A = [, , ], target = , k = ))
  48. print(s.kClosestNumbers(A = [, , , ], target = , k = ))
  49. print(s.kClosestNumbers(A = [,,,,], target = , k = ))
  50. print(s.kClosestNumbers(A = [,,,,,,,], target = , k = ))
  51. print(s.kClosestNumbers(A = [,,,,,,], target = , k = ))
  52. print(s.kClosestNumbers(A = [,,,], target = , k = ))

460

428. Pow(x,n)

  实现 pow(x, n). (n是一个整数,不用担心精度,当答案和标准输出差绝对值小于1e-3时都算正确)

Example

样例 1:

  1. 输入: x = 9.88023, n = 3
  2. 输出: 964.498

样例 2:

  1. 输入: x = 2.1, n = 3
  2. 输出: 9.261

样例 3:

  1. 输入: x = 1, n = 0
  2. 输出: 1
  1. #coding:utf-
  2.  
  3. class Solution:
  4.  
  5. def myPow(self,x,n):
  6. if n==:
  7. return
  8. elif n<:
  9. x = /x
  10. n = -n
  11. return recursive_pow(x,n)
  12.  
  13. def recursive_pow(x,n):
  14. if n==:
  15. return x
  16. else:
  17. half = recursive_pow(x,n//2)
  18. if n%==:
  19. return half*half*x
  20. else:
  21. return half*half
  22.  
  23. if __name__=="__main__":
  24. s = Solution()
  25. print(s.myPow(x = 9.88023, n = ))
  26. print(s.myPow(x = 2.1, n = ))
  27. print(s.myPow( x = , n = ))
  28. print(s.myPow( x = 2.00000, n = -))

428

 

159.Find Minimum Rotated Sorted Array

  假设一个排好序的数组在其某一未知点发生了旋转(比如0 1 2 4 5 6 7 可能变成4 5 6 7 0 1 2)。你需要找到其中最小的元素

Example

Example 1:

  1. 输入:[4, 5, 6, 7, 0, 1, 2]
  2. 输出:0
  3. 解释:
  4. 数组中的最小值为0

Example 2:

  1. 输入:[2,1]
  2. 输出:1
  3. 解释:
  4. 数组中的最小值为1
  1. #coding:utf-
  2. class Solution:
  3.  
  4. def findMin(self, nums):
  5.  
  6. length = len(nums)
  7. if length==:
  8. return nums[]
  9. elif length>:
  10. if nums[]<nums[-]:
  11. return nums[]
  12. else:
  13. left,right = ,length-
  14. while left<right:
  15. mid = (left+right)//
  16. if nums[mid]>nums[left]:
  17. left = mid
  18. elif nums[mid]<nums[left]:
  19. right = mid
  20. else: #mid和left相等时
  21. break
  22. return nums[right]
  23. if __name__=="__main__":
  24. s = Solution()
  25. print(s.findMin([, , , , , , ]))
  26. print(s.findMin([,]))

159

140. Fast Power

  计算an % b,其中a,b和n都是32位的非负整数。

Example

例如 231 % 3 = 2

例如 1001000 % 1000 = 0

Challenge

O(logn)

  1. #coding:utf-
  2.  
  3. #原理: (A*B)%p = ((A%p)*(B%p))%p
  4.  
  5. """
  6. @param a: A 32bit integer
  7. @param b: A 32bit integer
  8. @param n: A 32bit integer
  9. @return: An integer
  10. """
  11. class Solution:
  12.  
  13. def fastPower(self, a, b, n):
  14. if n==:
  15. return %b
  16. elif n==:
  17. return a%b
  18. else:
  19. half_remainder = self.fastPower(a,b,n//2)
  20. if n%==:
  21. return (half_remainder*half_remainder*a)%b
  22. else:
  23. return (half_remainder*half_remainder)%b
  24. if __name__=="__main__":
  25. s = Solution()
  26. print(s.fastPower(,,))
  27. print(s.fastPower(,,))
  28. print(s.fastPower(,,))

140

75. Find Peak Elements

  你给出一个整数数组(size为n),其具有以下特点:

  • 相邻位置的数字是不同的
  • A[0] < A[1] 并且 A[n - 2] > A[n - 1]

假定P是峰值的位置则满足A[P] > A[P-1]A[P] > A[P+1],返回数组中任意一个峰值的位置。

  • 数组保证至少存在一个峰
  • 如果数组存在多个峰,返回其中任意一个就行
  • 数组至少包含 3 个

Example

  1. 样例 1:
  2. 输入: [1, 2, 1, 3, 4, 5, 7, 6]
  3. 输出: 1 or 6
  4. 解释:
  5. 返回峰顶元素的下标
  6. 样例 2:
  7. 输入: [1,2,3,4,1]
  8. 输出: 3
  1. #coding:utf-
  2.  
  3. #参考题解:https://leetcode-cn.com/problems/find-peak-element/solution/hua-jie-suan-fa-162-xun-zhao-feng-zhi-by-guanpengc/
  4. #注意峰值的方向,先上升后下降
  5.  
  6. """
  7. @param A: An integers array.
  8. @return: return any of peek positions.
  9. """
  10. class Solution:
  11.  
  12. def findPeak(self, A):
  13. # write your code here
  14. length = len(A)
  15. if length==:
  16. return
  17. elif length>:
  18. left,right = , length-
  19. while left<right:
  20. mid = (left+right)//
  21. if A[mid]>A[mid+]: #下降趋势
  22. right = mid
  23. elif A[mid]<A[mid+]: #上升趋势
  24. left = mid+
  25. return left
  26. if __name__=="__main__":
  27. s = Solution()
  28. print(s.findPeak([, , , , , , , ]))
  29. print(s.findPeak([,,,,]))

75

74. First Bad Version

  代码库的版本号是从 1 到 n 的整数。某一天,有人提交了错误版本的代码,因此造成自身及之后版本的代码在单元测试中均出错。请找出第一个错误的版本号。

你可以通过 isBadVersion 的接口来判断版本号 version 是否在单元测试中出错,具体接口详情和调用方法请见代码的注释部分。

Example

  1. n = 5:
  2. isBadVersion(3) -> false
  3. isBadVersion(5) -> true
  4. isBadVersion(4) -> true
  5. 因此可以确定第四个版本是第一个错误版本。

Challenge

调用 isBadVersion 的次数越少越好

  1. Example
  2.  
  3. n = :
  4.  
  5. isBadVersion() -> false
  6. isBadVersion() -> true
  7. isBadVersion() -> true
  8.  
  9. 因此可以确定第四个版本是第一个错误版本。
  10.  
  11. Challenge
  12.  
  13. 调用 isBadVersion 的次数越少越好

74

 62. Search in Rotated Sorted Array

  假设有一个排序的按未知的旋转轴旋转的数组(比如,0 1 2 4 5 6 7 可能成为4 5 6 7 0 1 2)。给定一个目标值进行搜索,如果在数组中找到目标值返回数组中的索引位置,否则返回-1。你可以假设数组中不存在重复的元素。

Example

例1:

  1. 输入: [4, 5, 1, 2, 3] and target=1,
  2. 输出: 2.

例2:

  1. 输入: [4, 5, 1, 2, 3] and target=0,
  2. 输出: -1.

Challenge

O(logN) 时间限制

  1. class Solution:
  2. """
  3. @param A: an integer rotated sorted array
  4. @param target: an integer to be searched
  5. @return: an integer
  6. """
  7. def search(self, A, target):
  8. # write your code here
  9. length = len(A)
  10. if length>:
  11. left,right=,length-
  12. if A[]==target:
  13. return
  14. elif A[]>target:
  15. while left<=right:
  16. mid=(left+right)//
  17. if A[]<=A[mid]:
  18. left = mid+
  19. else:
  20. if A[mid]>target:
  21. right = mid-
  22. elif A[mid]<target:
  23. left = mid+
  24. else:
  25. return mid
  26. else:
  27. while left<=right:
  28. mid=(left+right)//
  29. if A[]>=A[mid]:
  30. right=mid-
  31. else:
  32. if A[mid]>target:
  33. right = mid-
  34. elif A[mid]<target:
  35. left = mid+
  36. else:
  37. return mid
  38. return -
  39. if __name__=="__main__":
  40. s = Solution()
  41. print(s.search([, , , , ],))
  42. print(s.search([, , , , ],))
  43. print(s.search([, ],))

62

(三). 双指针问题(Two Pointers)

 228. Middle of Linked List

  找链表的中点。

Example

样例 1:

  1. 输入: 1->2->3
  2. 输出: 2
  3. 样例解释: 返回中间节点的值

样例 2:

  1. 输入: 1->2
  2. 输出: 1
  3. 样例解释: 如果长度是偶数,则返回中间偏左的节点的值。

Challenge

如果链表是一个数据流,你可以不重新遍历链表的情况下得到中点么?

  1. #coding:utf-
  2.  
  3. #Definition of ListNode
  4. class ListNode(object):
  5. def __init__(self, val, next=None):
  6. self.val = val
  7. self.next = next
  8.  
  9. """
  10. @param head: the head of linked list.
  11. @return: a middle node of the linked list
  12. """
  13. class Solution:
  14.  
  15. def middleNode(self, head):
  16. # write your code here
  17. slow = fast = head
  18. if head:
  19. while fast.next!=None and fast.next.next!=None:
  20. slow = slow.next
  21. fast = fast.next.next
  22. return slow
  23. if __name__=="__main__":
  24. s = Solution()
  25. list1 = ListNode(,ListNode(,ListNode()))
  26. list2 = ListNode(,ListNode())
  27. print(s.middleNode(list1).val)
  28. print(s.middleNode(list2).val)

228

607 Two Sum III -Data structure design

  设计b并实现一个 TwoSum 类。他需要支持以下操作:addfind
    add -把这个数添加到内部的数据结构。
    find -是否存在任意一对数字之和等于这个值

Example

样例 1:

  1. add(1);add(3);add(5);
  2. find(4)//返回true
  3. find(7)//返回false
  1. #coding:utf-
  2.  
  3. #思路:遍历字典,求sum和遍历元素的差, 判断差是否也在字典中
  4. class TwoSum:
  5. """
  6. @param number: An integer
  7. @return: nothing
  8. """
  9. def __init__(self):
  10. self.numbers=dict()
  11.  
  12. def add(self, number):
  13. # write your code here
  14. if number not in self.numbers:
  15. self.numbers[number]=
  16. else:
  17. self.numbers[number]+=
  18.  
  19. """
  20. @param value: An integer
  21. @return: Find if there exists any pair of numbers which sum is equal to the value.
  22. """
  23. def find(self, value):
  24. # write your code here
  25. for key in self.numbers:
  26. target = value-key
  27. if target in self.numbers:
  28. if target!=key or self.numbers[target]>:
  29. return True
  30. return False
  31.  
  32. #按顺序插入列表,find时前后指针遍历
  33. # class TwoSum:
  34. # """
  35. # @param number: An integer
  36. # @return: nothing
  37. # """
  38. # def __init__(self):
  39. # self.numbers=[]
  40.  
  41. # def add(self, number):
  42. # # write your code here
  43. # length = len(self.numbers)
  44. # if length==:
  45. # self.numbers.append(number)
  46. # for i in range(length):
  47. # if self.numbers[i]>number:
  48. # self.numbers.insert(i,number)
  49. # break
  50. # if len(self.numbers)==length:
  51. # self.numbers.append(number)
  52.  
  53. # """
  54. # @param value: An integer
  55. # @return: Find if there exists any pair of numbers which sum is equal to the value.
  56. # """
  57. # def find(self, value):
  58. # # write your code here
  59. # i,j=,len(self.numbers)-
  60. # while i<j:
  61. # if self.numbers[i]+self.numbers[j]==value:
  62. # return True
  63. # elif self.numbers[i]+self.numbers[j]>value:
  64. # j = j-
  65. # else:
  66. # i = i+
  67. # return False
  68. if __name__=="__main__":
  69. s = TwoSum()
  70. # s.add()
  71. # s.add()
  72. # s.add()
  73. # print(s.find())
  74. # print(s.find())
  75.  
  76. # s.add()
  77. # s.add()
  78. # print(s.find())
  79. # print(s.find())
  80. # print(s.find())
  81. # s.add()
  82. # print(s.find())
  83.  
  84. s.add()
  85. s.add()
  86. s.add()
  87. print(s.find())
  88. s.add()
  89. print(s.find())
  90. print(s.find())
  91. s.add()
  92. print(s.find())
  93. print(s.find())

607

539. Move Zeros

  给一个数组 nums 写一个函数将 0 移动到数组的最后面,非零元素保持原数组的顺序

    1.必须在原数组上操作
    2.最小化操作数

Example

例1:

  1. 输入: nums = [0, 1, 0, 3, 12],
  2. 输出: [1, 3, 12, 0, 0].

例2:

  1. 输入: nums = [0, 0, 0, 3, 1],
  2. 输出: [3, 1, 0, 0, 0].
  1. #coding:utf-
  2.  
  3. """
  4. 思路:
  5. 快慢指针:假设我们有一个新数组,有 根指针分别从老数组和新数组从前往后走,称老数组上的指针为「读指针」,新数组上的指针为「写指针」;只有当读指针所指向的数值非0时,才将读指针所指的数值写入到写指针所指的空间上,然后两根指针再继续向前走;当老数组遍历完时,只要将新数组继续填 直到新老数组长度一致即可。题目要求「就地操作」,那么实际上就不需要开这个新数组,只要让两根指针都在原数组上往前走就行:这是因为,读指针由于会跳过非 空间,其扫描速度远快于写指针,所有被读指针扫描过的非零值都会通过写指针写入「新的空间」中,因此所有被写指针覆盖掉的非零值,之前必定已经保存过了。该方法时间复杂度 O(n),空间复杂度 O()
  6. """
  7.  
  8. """
  9. @param nums: an integer array
  10. @return: nothing
  11. """
  12. class Solution:
  13.  
  14. def moveZeroes(self, nums):
  15. # write your code here
  16. i=j=
  17. while i<len(nums):
  18. if nums[i]!=:
  19. nums[j]=nums[i]
  20. j = j+
  21. i = i+
  22. while j<i:
  23. nums[j]=
  24. j = j+
  25. return nums
  26. if __name__=="__main__":
  27. s = Solution()
  28. print(s.moveZeroes([, , , , ]))
  29. print(s.moveZeroes([, , , , ]))

539


521 Remove Duplicate Numbers in Array

  给一个整数数组,去除重复的元素。

  你应该做这些事

    1.在原数组上操作
    2.将去除重复之后的元素放在数组的开头
    3.返回去除重复元素之后的元素个数

Example

例1:

  1. 输入:
  2. nums = [1,3,1,4,4,2]
  3. 输出:
  4. nums变为[1,3,4,2,?,?])
  5. 4
  6. 解释:
  7. 1. 将重复的整数移动到 nums 的尾部 => nums = [1,3,4,2,?,?].
  8. 2. 返回 nums 中唯一整数的数量 => 4.
  9. 事实上我们并不关心你把什么放在了 ? 处, 只关心没有重复整数的部分.

例2:

  1. 输入:
  2. nums = [1,2,3]
  3. 输出:
    (nums变为[1,2,3])
  4. 3
  1. #coding:utf-
  2.  
  3. """
  4. @param nums: an array of integers
  5. @return: the number of unique integers
  6. """
  7.  
  8. #时间复杂度O(n),空间复杂度O(n)
  9. class Solution:
  10.  
  11. def deduplication(self, nums):
  12. # write your code here
  13. nums_set=set()
  14. i=
  15. for num in nums:
  16. if num not in nums_set:
  17. nums_set.add(num)
  18. nums[i]=num
  19. i = i+
  20.  
  21. return i
  22.  
  23. #排序后使用双指针,时间复杂度O(nlogn),空间复杂度O()
  24. # class Solution:
  25.  
  26. # def deduplication(self, nums):
  27. # # write your code here
  28. # length = len(nums)
  29. # if length<=:
  30. # return length
  31. # quicksort(nums,,length-)
  32. # i=j =
  33. # while i<length:
  34. # if nums[i]!=nums[i-]:
  35. # nums[j]=nums[i]
  36. # j = j+
  37. # i = i+
  38. # return j
  39.  
  40. # def quicksort(nums,start,end):
  41. # if start<end:
  42. # pivot = start
  43. # left,right=start+,end
  44. # while left<=right:
  45. # while left<=right and nums[left]<=nums[pivot]:
  46. # left = left+
  47. # while left<=right and nums[right]>nums[pivot]:
  48. # right= right-
  49. # if left<=right:
  50. # nums[left],nums[right]=nums[right],nums[left]
  51. # nums[right],nums[pivot]=nums[pivot],nums[right]
  52. # quicksort(nums,start,right-)
  53. # quicksort(nums,right+,end)
  54.  
  55. if __name__=="__main__":
  56.  
  57. s = Solution()
  58. print(s.deduplication([,,,,,]))
  59. print(s.deduplication(nums = [,,]))

521

464 Sort Integers II

  给一组整数,请将其在原地按照升序排序。使用归并排序,快速排序,堆排序或者任何其他 O(n log n) 的排序算法。

Description

中文
English

给一组整数,请将其在原地按照升序排序。使用归并排序,快速排序,堆排序或者任何其他 O(n log n) 的排序算法。

Have you met this question in a real interview?  

Example

例1:

  1. 输入:[3,2,1,4,5],
  2. 输出:[1,2,3,4,5]。

例2:

  1. 输入:[2,3,1],
  2. 输出:[1,2,3]。
  1. """
  2. @param A: an integer array
  3. @return: nothing
  4. """
  5. class Solution:
  6.  
  7. def sortIntegers2(self, A):
  8. # write your code here
  9. quicksort(A,,len(A)-)
  10. return A
  11.  
  12. def quicksort(alist,start,end):
  13. if start<end:
  14. pivot=alist[start]
  15. left,right = start,end
  16. while left<right:
  17. while left<right and alist[right]>=pivot:
  18. right-=
  19. alist[left],alist[right]=alist[right],alist[left]
  20. while left<right and alist[left]<=pivot:
  21. left+=
  22. alist[right],alist[left]=alist[left],alist[right]
  23. quicksort(alist,start,left-)
  24. quicksort(alist,left+,end)
  25. if __name__=="__main__":
  26. s = Solution()
  27. print(s.sortIntegers2([, , , , ]))
  28. print(s.sortIntegers2([, , ]))

464

608. Two Sum II- Input array is sorted

  给定一个已经 按升序排列 的数组,找到两个数使他们加起来的和等于特定数。
  函数应该返回这两个数的下标,index1必须小于index2。注意返回的值不是 0-based

Example

例1:

  1. 输入: nums = [2, 7, 11, 15], target = 9
  2. 输出: [1, 2]

例2:

  1. 输入: nums = [2,3], target = 5
  2. 输出: [1, 2]
  1. class Solution:
  2. """
  3. @param nums: an array of Integer
  4. @param target: target = nums[index1] + nums[index2]
  5. @return: [index1 + , index2 + ] (index1 < index2)
  6. """
  7. def twoSum(self, nums, target):
  8. # write your code here
  9. length = len(nums)
  10. if length>:
  11. i,j=,length-
  12. while i<j:
  13. if nums[i]+nums[j]==target:
  14. return i+,j+
  15. elif nums[i]+nums[j]<target:
  16. i+=
  17. else:
  18. j-=
  19. if __name__=="__main__":
  20. s = Solution()
  21. print(s.twoSum(nums = [, , , ], target = ))
  22. print(s.twoSum(nums = [,], target = ))

608

143 Sort Colors II

  给定一个有n个对象(包括k种不同的颜色,并按照1到k进行编号)的数组,将对象进行分类使相同颜色的对象相邻,并按照1,2,...k的顺序进行排序。

  1. 不能使用代码库中的排序函数来解决这个问题
  2. k <= n

Example

样例1

  1. 输入:
  2. [3,2,2,1,4]
  3. 4
  4. 输出:
  5. [1,2,2,3,4]

样例2

  1. 输入:
  2. [2,1,1,2,2]
  3. 2
  4. 输出:
  5. [1,1,2,2,2]

Challenge

一个相当直接的解决方案是使用计数排序扫描2遍的算法。这样你会花费O(k)的额外空间。你否能在不使用额外空间的情况下完成?

  1. #coding:utf-
  2.  
  3. #思路参考:https://www.cnblogs.com/libaoquan/p/7226211.html (计数排序/桶排序改进)
  4. #输入[,,,,],进行一次遍历后变化过程如下:
  5. # [, , , , ]
  6. # [, , -, , ]
  7. # [, -, -, , ]
  8. # [, -, -, , ]
  9. # [-, -, -, , ]
  10. # [-, -, -, -, ]
  11.  
  12. """
  13. @param colors: A list of integer
  14. @param k: An integer
  15. @return: nothing
  16. """
  17. class Solution:
  18.  
  19. def sortColors2(self, colors, k):
  20. length = len(colors)
  21. if length<=:
  22. return colors
  23. #统计计数
  24. for i in range(length):
  25. while colors[i]>:
  26. index = colors[i]
  27. if colors[index-]>:
  28. colors[i]=colors[index-]
  29. colors[index-]=- #表示index出现一次
  30. elif colors[index-]<=:
  31. colors[i]=
  32. colors[index-]-= #表示index再次出现
  33.  
  34. #输出排序结果
  35. j=length-
  36. for i in range(k-,-,-):
  37. temp = colors[i]
  38. while temp<:
  39. colors[j]=i+
  40. temp+=
  41. j-=
  42. return colors
  43. if __name__=="__main__":
  44. s = Solution()
  45. print(s.sortColors2([,,,,],))
  46. print(s.sortColors2([,,,,],))

143

57. Three Sum

Description:
    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
    Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
    The solution set must not contain duplicate triplets.

Example 1:
    Input:[2,7,11,15]
    Output:[]
    
Example 2:
    Input:[-1,0,1,2,-1,-4]
    Output:    [[-1, 0, 1],[-1, -1, 2]]

  1. #coding:utf-
  2.  
  3. """
  4. 题目: Three Sum
  5. Description:
  6. Given an array S of n integers, are there elements a, b, c in S such that a + b + c = ? Find all unique triplets in the array which gives the sum of zero.
  7. Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  8. The solution set must not contain duplicate triplets.
  9.  
  10. Example :
  11. Input:[,,,]
  12. Output:[]
  13.  
  14. Example :
  15. Input:[-,,,,-,-]
  16. Output: [[-, , ],[-, -, ]]
  17. """
  18.  
  19. """
  20. 思路:
  21. 由于设置了三个变量,故时间复杂度最少是O(n^)
  22. 在开头固定一个变量,然后一前一后 移动指针
  23. 和大于零 后指针前移
  24. 和小于零 前指针后移
  25. 和等于零 放入结果中,再让前后指针移动
  26. """
  27.  
  28. """
  29. @param numbers: Give an array numbers of n integer
  30. @return: Find all unique triplets in the array which gives the sum of zero.
  31. """
  32. class Solution:
  33.  
  34. def threeSum(self, numbers):
  35. # write your code here
  36. length = len(numbers)
  37. ret=[]
  38. if length<:
  39. return ret
  40. quicksort(numbers,,length-)
  41. print(numbers)
  42. for k in range(length-):
  43. if k== or numbers[k]!=numbers[k-]: #防止重复
  44. twoSum(numbers,-numbers[k],start=k+,end=length-,ret=ret)
  45. return ret
  46.  
  47. def quicksort(numbers,start,end):
  48. if start<end:
  49. left,right=start,end
  50. pivot = numbers[start]
  51. while left<right:
  52. while left<right and numbers[right]>=pivot:
  53. right-=
  54. numbers[right],numbers[left]=numbers[left],numbers[right]
  55. while left<right and numbers[left]<pivot:
  56. left+=
  57. numbers[right],numbers[left]=numbers[left],numbers[right]
  58. quicksort(numbers,start,right-)
  59. quicksort(numbers,right+,end)
  60.  
  61. def twoSum(numbers,target,start,end,ret):
  62. i,j = start,end
  63. while i<j:
  64. if numbers[i]+numbers[j]<target:
  65. i+=
  66. elif numbers[i]+numbers[j]>target:
  67. j-=
  68. else:
  69. if (-target)<numbers[i]:
  70. temp=[-target,numbers[i],numbers[j]]
  71. elif (-target)>numbers[j]:
  72. temp=[numbers[i],numbers[j],-target]
  73. else:
  74. temp=[numbers[i],-target,numbers[j]]
  75. if temp not in ret: #防止重复
  76. ret.append(temp)
  77. i+=
  78. j-=
  79.  
  80. if __name__=="__main__":
  81. s = Solution()
  82. # print(s.threeSum([,,,]))
  83. # print(s.threeSum([-,,,,-,-]))
  84. # print(s.threeSum([,,-,-,-,-,,,,]))
  85. print(s.threeSum([-,-,-,-,-,,,,,,,,,-,,,,]))

57

31.Partition Array

Description
    Given an array nums of integers and an int k, partition the array (i.e move the elements in "nums") such that:

All elements < k are moved to the left
        All elements >= k are moved to the right

Return the partitioning index, i.e the first index i nums[i] >= k.
    You should do really partition in array nums instead of just counting the numbers of integers smaller than k.
    If all elements in nums are smaller than k, then return nums.length

Example 1:
    Input:
    [],9
    Output:
    0

Example 2:
    Input:
    [3,2,2,1],2
    Output:1
    Explanation:
    the real array is[1,2,2,3].So return 1

Challenge
    Can you partition the array in-place and in O(n)?

  1. #coding:utf-
  2.  
  3. """
  4. Description
  5. Given an array nums of integers and an int k, partition the array (i.e move the elements in "nums") such that:
  6.  
  7. All elements < k are moved to the left
  8. All elements >= k are moved to the right
  9.  
  10. Return the partitioning index, i.e the first index i nums[i] >= k.
  11. You should do really partition in array nums instead of just counting the numbers of integers smaller than k.
  12. If all elements in nums are smaller than k, then return nums.length
  13.  
  14. Example :
  15. Input:
  16. [],
  17. Output:
  18.  
  19. Example :
  20. Input:
  21. [,,,],
  22. Output:
  23. Explanation:
  24. the real array is[,,,].So return
  25.  
  26. Challenge
  27. Can you partition the array in-place and in O(n)?
  28. """
  29.  
  30. """
  31. 思路:类似于快速排序的左右指针
  32. """
  33.  
  34. class Solution:
  35. """
  36. @param nums: The integer array you should partition
  37. @param k: An integer
  38. @return: The index after partition
  39. """
  40. def partitionArray(self, nums, k):
  41. # write your code here
  42. length=len(nums)
  43. if length==:
  44. return
  45. i,j=,length-
  46. while i<=j:
  47. while i<=j and nums[i]<k:
  48. i+=
  49. while i<=j and nums[j]>=k:
  50. j-=
  51. if i<j:
  52. nums[i],nums[j]=nums[j],nums[i]
  53. return i
  54. if __name__=="__main__":
  55. s = Solution()
  56. print(s.partitionArray([],))
  57. print(s.partitionArray([,,,],))

31

5. Kth Largest Element
Description

Find K-th largest element in an array.
    You can swap elements in the array

Example 1:
    Input:
    n = 1, nums = [1,3,4,2]
    Output:
    4

Example 2:
    Input:
    n = 3, nums = [9,3,2,4,8]
    Output:
    4

Challenge
    O(n) time, O(1) extra memory.

  1. #coding:utf-
  2.  
  3. """
  4. 题目:. Kth Largest Element
  5. Description
  6.  
  7. Find K-th largest element in an array.
  8. You can swap elements in the array
  9.  
  10. Example :
  11. Input:
  12. n = , nums = [,,,]
  13. Output:
  14.  
  15. Example :
  16. Input:
  17. n = , nums = [,,,,]
  18. Output:
  19.  
  20. Challenge
  21. O(n) time, O() extra memory.
  22. """
  23. """
  24. 思路:
  25. 快速选择算法 的平均时间复杂度为 O(N){O}(N)O(N)。就像快速排序那样,本算法也是 Tony Hoare 发明的,因此也被称为 Hoare选择算法。
  26.  
  27. 本方法大致上与快速排序相同。简便起见,注意到第 k 个最大元素也就是第 N - k 个最小元素,因此可以用第 k 小算法来解决本问题。
  28.  
  29. 首先,我们选择一个枢轴,并在线性时间内定义其在排序数组中的位置。这可以通过 划分算法 的帮助来完成。
  30.  
  31. 为了实现划分,沿着数组移动,将每个元素与枢轴进行比较,并将小于枢轴的所有元素移动到枢轴的左侧。
  32.  
  33. 这样,在输出的数组中,枢轴达到其合适位置。所有小于枢轴的元素都在其左侧,所有大于或等于的元素都在其右侧。
  34.  
  35. 这样,数组就被分成了两部分。如果是快速排序算法,会在这里递归地对两部分进行快速排序,时间复杂度为 O(Nlog⁡N)。
  36.  
  37. 而在这里,由于知道要找的第 N - k 小的元素在哪部分中,我们不需要对两部分都做处理,这样就将平均时间复杂度下降到 O(N)。
  38.  
  39. """
  40. class Solution:
  41. """
  42. @param n: An integer
  43. @param nums: An array
  44. @return: the Kth largest element
  45. """
  46. def kthLargestElement(self, n, nums):
  47. # write your code here
  48. length = len(nums)
  49. if n>length or n==:
  50. return None
  51. return half_quicksort(nums,n,,length-)
  52.  
  53. #方法二,利用二叉堆
  54. def kthLargestElement2(self, n, nums):
  55. import heapq
  56. length = len(nums)
  57. if n>length or n==:
  58. return None
  59. return heapq.nlargest(n,nums)[n-]
  60.  
  61. def half_quicksort(nums,k,start,end):
  62. if k== and start==end:
  63. return nums[start]
  64. if start<end:
  65. left,right=start,end
  66. pivot = nums[start]
  67. while left<right:
  68. while left<right and nums[right]>=pivot:
  69. right-=
  70. nums[left],nums[right]=nums[right],nums[left]
  71. while left<right and nums[left]<pivot:
  72. left+=
  73. nums[left],nums[right]=nums[right],nums[left]
  74.  
  75. if end-right>k-:
  76. return half_quicksort(nums,k,right+,end)
  77. elif end-right<k-:
  78. return half_quicksort(nums,k-(end-right+),start,right-)
  79. else:
  80. return nums[right]
  81.  
  82. if __name__=="__main__":
  83. s = Solution()
  84. print(s.kthLargestElement(n = , nums = [,,,]))
  85. print(s.kthLargestElement(n = , nums = [,,,,]))
  86.  
  87. print(s.kthLargestElement2(n = , nums = [,,,]))
  88. print(s.kthLargestElement2(n = , nums = [,,,,]))

5

(四). 宽度优先搜索和拓扑排序(BFS and Topplogical Sort)

433. Number of Islands

Description

  Given a boolean 2D matrix, 0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent.
        Find the number of islands.

Example 1:
    Input:
    [
      [1,1,0,0,0],
      [0,1,0,0,1],
      [0,0,0,1,1],
      [0,0,0,0,0],
      [0,0,0,0,1]
    ]
    Output:3

Example 2:

Input:
    [
      [1,1]
    ]
    Output:1

  1. #coding:utf-
  2.  
  3. """
  4. . Number of Islands
  5.  
  6. Given a boolean 2D matrix, is represented as the sea, is represented as the island. If two is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent.
  7.  
  8. Find the number of islands.
  9. Example
  10.  
  11. Example :
  12. Input:
  13. [
  14. [,,,,],
  15. [,,,,],
  16. [,,,,],
  17. [,,,,],
  18. [,,,,]
  19. ]
  20. Output:
  21.  
  22. Example :
  23.  
  24. Input:
  25. [
  26. [,]
  27. ]
  28. Output:
  29. """
  30. """
  31. 思路:线性扫描整个二维网格,如果一个结点包含 ,则以其为根结点启动深度优先搜索。在深度优先搜索过程中,每个访问过的结点被标记为 。计数启动深度优先搜索的根结点的数量,即为岛屿的数量。
  32. """
  33. class Solution:
  34. """
  35. @param grid: a boolean 2D matrix
  36. @return: an integer
  37. """
  38. def numIslands(self, grid):
  39. # write your code here
  40. rows = len(grid)
  41. nums =
  42. if rows==:
  43. return nums
  44. for r in range(rows):
  45. cols = len(grid[r])
  46. if cols>:
  47. for c in range(cols):
  48. if grid[r][c]==:
  49. dfs(grid,r,c)
  50. nums+=
  51. return nums
  52.  
  53. def dfs(grid,r,c):
  54. rows = len(grid)
  55. if r< or r>rows-:
  56. return
  57.  
  58. cols = len(grid[r])
  59. if c< or c>cols-:
  60. return
  61. if grid[r][c]==:
  62. return
  63. grid[r][c]= #grid[r][c]=,将其由1设置为0,表示已经遍历
  64. dfs(grid,r-,c)
  65. dfs(grid,r+,c)
  66. dfs(grid,r,c-)
  67. dfs(grid,r,c+)
  68.  
  69. if __name__=="__main__":
  70. s = Solution()
  71. g1 =[
  72. [,,,,],
  73. [,,,,],
  74. [,,,,],
  75. [,,,,],
  76. [,,,,]
  77. ]
  78. g2=[
  79. [,]
  80. ]
  81. print(s.numIslands(g1))
  82. print(s.numIslands(g2))

433

69. Binary Tree Level Order Traversal

Description
    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

The first data is the root node, followed by the value of the left and right son nodes, and "#" indicates that there is no child node.
        The number of nodes does not exceed 20.

Example 1:

Input:{1,2,3}
    Output:[[1],[2,3]]
    Explanation:
      1
     / \
    2   3
    it will be serialized {1,2,3}
    level order traversal

Example 2:

Input:{1,#,2,3}
    Output:[[1],[2],[3]]
    Explanation:
    1
     \
      2
     /
    3
    it will be serialized {1,#,2,3}
    level order traversal

Challenge
    Challenge 1: Using only 1 queue to implement it.
    Challenge 2: Use BFS algorithm to do it.

  1. #coding:utf-
  2.  
  3. """
  4. 题目:. Binary Tree Level Order Traversal
  5. Description
  6. Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
  7.  
  8. The first data is the root node, followed by the value of the left and right son nodes, and "#" indicates that there is no child node.
  9. The number of nodes does not exceed .
  10.  
  11. Example :
  12.  
  13. Input:{,,}
  14. Output:[[],[,]]
  15. Explanation
  16.  
  17. / \
  18.  
  19. it will be serialized {,,}
  20. level order traversal
  21.  
  22. Example :
  23.  
  24. Input:{,#,,}
  25. Output:[[],[],[]]
  26. Explanation
  27.  
  28. \
  29.  
  30. /
  31.  
  32. it will be serialized {,#,,}
  33. level order traversal
  34.  
  35. Challenge
  36. Challenge : Using only queue to implement it.
  37. Challenge : Use BFS algorithm to do it.
  38. """
  39.  
  40. #Definition of TreeNode:
  41. class TreeNode:
  42. def __init__(self, val,left=None,right=None):
  43. self.val = val
  44. self.left, self.right = left, right
  45.  
  46. class Solution:
  47. """
  48. @param root: A Tree
  49. @return: Level order a list of lists of integer
  50. """
  51. def levelOrder(self, root):
  52. # write your code here
  53. if not root:
  54. return []
  55. q=[[root]]
  56. ret=[]
  57. while q:
  58. val,temp=[],[]
  59. cur_list = q.pop()
  60. for cur in cur_list:
  61. if cur.left:
  62. temp.append(cur.left)
  63. if cur.right:
  64. temp.append(cur.right)
  65. if cur.val!="#":
  66. val.append(cur.val)
  67. if temp:
  68. q.append(temp)
  69. if val:
  70. ret.append(val)
  71. return ret
  72.  
  73. if __name__=="__main__":
  74. s = Solution()
  75. #{,,}
  76. t1 = TreeNode(,TreeNode(),TreeNode())
  77. print(s.levelOrder(t1))
  78. #{,#,,}
  79. t2 = TreeNode(,TreeNode("#"),TreeNode(,TreeNode()))
  80. print(s.levelOrder(t2))

69

615 Course Schedule

Description

There are a total of n courses you have to take, labeled from 0 to n - 1.
    Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
    Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

Example 1:
    Input: n = 2, prerequisites = [[1,0]]
    Output: true

Example 2:
    Input: n = 2, prerequisites = [[1,0],[0,1]]
    Output: false

  1. #coding:utf-
  2.  
  3. """
  4. Description
  5.  
  6. There are a total of n courses you have to take, labeled from to n - .
  7. Some courses may have prerequisites, for example to take course you have to first take course , which is expressed as a pair: [,]
  8. Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
  9.  
  10. Example :
  11. Input: n = , prerequisites = [[,]]
  12. Output: true
  13.  
  14. Example :
  15. Input: n = , prerequisites = [[,],[,]]
  16. Output: false
  17. """
  18.  
  19. #思路:参考https://leetcode-cn.com/problems/course-schedule/solution/tuo-bu-pai-xu-by-liweiwei1419/
  20. """
  21. 拓扑排序
  22. 具体做如下:
  23.  
  24. 、在开始排序前,扫描对应的存储空间(使用邻接表),将入度为 的结点放入队列。
  25.  
  26. 、只要队列非空,就从队首取出入度为 的结点,将这个结点输出到结果集中,并且将这个结点的所有邻接结点(它指向的结点)的入度减 ,在减 以后,如果这个被减 的结点的入度为 ,就继续入队。
  27.  
  28. 、当队列为空的时候,检查结果集中的顶点个数是否和课程数相等即可。
  29.  
  30. """
  31.  
  32. class Solution:
  33. """
  34. @param: numCourses: a total of n courses
  35. @param: prerequisites: a list of prerequisite pairs
  36. @return: true if can finish all courses or false
  37. """
  38. def canFinish(self, numCourses, prerequisites):
  39. # write your code here
  40. length = len(prerequisites)
  41. if length==:
  42. return True
  43.  
  44. #初始化入度和邻接表(邻接表存放的是后继 successor 结点的集合)
  45. degree = [ for i in range(numCourses)]
  46. adj = [set() for i in range(numCourses)]
  47.  
  48. # 想要学习课程 ,你需要先完成课程 ,我们用一个匹配来表示他们: [,]
  49. # [, ] 表示 在先, 在后,1的后继节点为0 (所以0这个节点的度加一)
  50. for second, first in prerequisites:
  51. if second not in adj[first]: #避免重复
  52. degree[second]+=
  53. adj[first].add(second)
  54.  
  55. p=[]
  56. count =
  57. for i in range(len(degree)):
  58. if degree[i]==:
  59. p.append(i)
  60. while p:
  61. cur = p.pop()
  62. for j in adj[cur]:
  63. degree[j]-=
  64. if degree[j]==:
  65. p.append(j)
  66. count+=
  67. if count==numCourses:
  68. return True
  69. return False
  70. if __name__=="__main__":
  71. s = Solution()
  72. # print(s.canFinish(, prerequisites = [[,]] ))
  73. # print(s.canFinish(, prerequisites = [[,],[,]] ))
  74. print(s.canFinish(, prerequisites = [[,],[,],[,],[,],[,],[,],[,],[,]] ))

615

615 Course Schedule II

Description
    There are a total of n courses you have to take, labeled from 0 to n - 1.
    Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
    Have you met this question in a real interview?  
    Example

Example 1:
    Input: n = 2, prerequisites = [[1,0]]
    Output: [0,1]

Example 2:
    Input: n = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
    Output: [0,1,2,3] or [0,2,1,3]

  1. #coding:utf-
  2.  
  3. """
  4. Description
  5. There are a total of n courses you have to take, labeled from to n - .
  6. Some courses may have prerequisites, for example to take course you have to first take course , which is expressed as a pair: [,]
  7.  
  8. Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
  9.  
  10. There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
  11. Have you met this question in a real interview?
  12. Example
  13.  
  14. Example :
  15. Input: n = , prerequisites = [[,]]
  16. Output: [,]
  17.  
  18. Example :
  19. Input: n = , prerequisites = [[,],[,],[,],[,]]
  20. Output: [,,,] or [,,,]
  21. """
  22.  
  23. class Solution:
  24. """
  25. @param: numCourses: a total of n courses
  26. @param: prerequisites: a list of prerequisite pairs
  27. @return: the course order
  28. """
  29. def findOrder(self, numCourses, prerequisites):
  30. # write your code here
  31. length = len(prerequisites)
  32. if length==:
  33. return [i for i in range(numCourses)]
  34.  
  35. #初始化入度和邻接表(邻接表存放的是后继 successor 结点的集合)
  36. degree = [ for i in range(numCourses)]
  37. adj = [set() for i in range(numCourses)]
  38.  
  39. # 想要学习课程 ,你需要先完成课程 ,我们用一个匹配来表示他们: [,]
  40. # [, ] 表示 在先, 在后,1的后继节点为0 (所以0这个节点的度加一)
  41. for second, first in prerequisites:
  42. if second not in adj[first]: #避免重复
  43. degree[second]+=
  44. adj[first].add(second)
  45.  
  46. p=[]
  47. course = []
  48. for i in range(len(degree)):
  49. if degree[i]==:
  50. p.append(i)
  51. while p:
  52. cur = p.pop()
  53. for j in adj[cur]:
  54. degree[j]-=
  55. if degree[j]==:
  56. p.append(j)
  57. course.append(cur)
  58. if len(course)==numCourses:
  59. return course
  60. return []
  61.  
  62. if __name__=="__main__":
  63. s = Solution()
  64. print(s.findOrder(, prerequisites = [[,]] ))
  65. print(s.findOrder(, prerequisites = [[,],[,],[,],[,]] ))

616

605 Sequence Reconstruction

Description
    Check whether the original sequence org can be uniquely reconstructed from the sequences in seqs. The org sequence is a permutation of the integers from 1 to n, with 1 ≤ n ≤ 10^4.
    Reconstruction means building a shortest common supersequence of the sequences in seqs (i.e., a shortest sequence so that all sequences in seqs are subsequences of it).
    Determine whether there is only one sequence that can be reconstructed from seqs and it is the org sequence.

Example 1:
    Input:org = [1,2,3], seqs = [[1,2],[1,3]]
    Output: false
    Explanation:
    [1,2,3] is not the only one sequence that can be reconstructed, because [1,3,2] is also a valid sequence that can be reconstructed.

Example 2:
    Input: org = [1,2,3], seqs = [[1,2]]
    Output: false
    Explanation:
    The reconstructed sequence can only be [1,2].

Example 3:
    Input: org = [1,2,3], seqs = [[1,2],[1,3],[2,3]]
    Output: true
    Explanation:
    The sequences [1,2], [1,3], and [2,3] can uniquely reconstruct the original sequence [1,2,3].

Example 4:
    Input:org = [4,1,5,2,6,3], seqs = [[5,2,6,3],[4,1,5,2]]
    Output:true

  1. #coding:utf-
  2. """
  3. Description
  4. Check whether the original sequence org can be uniquely reconstructed from the sequences in seqs. The org sequence is a permutation of the integers from to n, with ≤ n ≤ ^.
  5. Reconstruction means building a shortest common supersequence of the sequences in seqs (i.e., a shortest sequence so that all sequences in seqs are subsequences of it).
  6. Determine whether there is only one sequence that can be reconstructed from seqs and it is the org sequence.
  7.  
  8. Example :
  9. Input:org = [,,], seqs = [[,],[,]]
  10. Output: false
  11. Explanation:
  12. [,,] is not the only one sequence that can be reconstructed, because [,,] is also a valid sequence that can be reconstructed.
  13.  
  14. Example :
  15. Input: org = [,,], seqs = [[,]]
  16. Output: false
  17. Explanation:
  18. The reconstructed sequence can only be [,].
  19.  
  20. Example :
  21. Input: org = [,,], seqs = [[,],[,],[,]]
  22. Output: true
  23. Explanation:
  24. The sequences [,], [,], and [,] can uniquely reconstruct the original sequence [,,].
  25.  
  26. Example :
  27. Input:org = [,,,,,], seqs = [[,,,],[,,,]]
  28. Output:true
  29.  
  30. """
  31. # 拓扑排序:构建图和入度,按顺序遍历,验证唯一性
  32. # 拓扑排序的四种问法:
  33. # 求任意一个拓扑排序。
  34. # 问是否存在拓扑排序(course schedule )
  35. # 求所有拓扑排序(DFS)
  36. # 求是否存在且仅存在一个拓扑排序 (Queue中最多只有一个节点)
  37.  
  38. class Solution:
  39. """
  40. @param org: a permutation of the integers from to n
  41. @param seqs: a list of sequences
  42. @return: true if it can be reconstructed only one or false
  43. """
  44. def sequenceReconstruction(self, org, seqs):
  45. # write your code here
  46. from collections import defaultdict
  47. # if len(seqs)== or len(org)==:
  48. # return False
  49.  
  50. degree=dict()
  51. adj=defaultdict(set)
  52. for seq in seqs:
  53. for i in range(,len(seq)):
  54. if seq[i] not in degree:
  55. degree[seq[i]]=
  56. if i+<len(seq) and seq[i+] not in adj[seq[i]]:
  57. adj[seq[i]].add(seq[i+])
  58. if seq[i+] not in degree:
  59. degree[seq[i+]]=
  60. else:
  61. degree[seq[i+]]+=
  62.  
  63. q=[i for i in degree.keys() if degree[i]==]
  64. ret=[]
  65. while q:
  66. cur = q.pop()
  67. for cur_adj in adj[cur]:
  68. degree[cur_adj]-=
  69. if degree[cur_adj]==:
  70. q.append(cur_adj)
  71. ret.append(cur)
  72. if ret==org: #可能有多个顺序,若相等则是唯一性
  73. return True
  74. return False
  75. if __name__=="__main__":
  76. s = Solution()
  77. print(s.sequenceReconstruction(org = [], seqs = [[]]))
  78. print(s.sequenceReconstruction(org = [,,], seqs = [[,],[,]]))
  79. print(s.sequenceReconstruction(org = [,,], seqs = [[,]]))
  80. print(s.sequenceReconstruction(org = [,,], seqs = [[,],[,],[,]]))
  81. print(s.sequenceReconstruction(org = [,,,,,], seqs = [[,,,],[,,,]]))

605

137 Clone Graph
Description
    Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. Nodes are labeled uniquely.
    You need to return a deep copied graph, which has the same structure as the original graph,
    and any changes to the new graph will not have any effect on the original graph.

Clarification:

{1,2,4#2,1,4#3,5#4,1,2#5,3} represents follow graph:

1------2  3
     \     |  |
      \    |  |
       \   |  |
        \  |  |
          4   5

we use # to split each node information.
    1,2,4 represents that 2, 4 are 1's neighbors
    2,1,4 represents that 1, 4 are 2's neighbors
    3,5 represents that 5 is 3's neighbor
    4,1,2 represents that 1, 2 are 4's neighbors
    5,3 represents that 3 is 5's neighbor

Example1
    Input:
    {1,2,4#2,1,4#4,1,2}
    Output:
    {1,2,4#2,1,4#4,1,2}
    Explanation:
    1------2  
     \     |  
      \    |  
       \   |  
        \  |  
          4

  1. #coding:utf
  2.  
  3. """
  4. Clone Graph
  5. Description
  6. Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. Nodes are labeled uniquely.
  7. You need to return a deep copied graph, which has the same structure as the original graph,
  8. and any changes to the new graph will not have any effect on the original graph.
  9.  
  10. Clarification:
  11.  
  12. {,,#,,#,#,,#,} represents follow graph:
  13.  
  14. ------
  15. \ | |
  16. \ | |
  17. \ | |
  18. \ | |
  19.  
  20. we use # to split each node information.
  21. ,, represents that , are 's neighbors
  22. ,, represents that , are 's neighbors
  23. , represents that is 's neighbor
  24. ,, represents that , are 's neighbors
  25. , represents that is 's neighbor
  26.  
  27. Example1
  28. Input:
  29. {,,#,,#,,}
  30. Output:
  31. {,,#,,#,,}
  32. Explanation:
  33. ------
  34. \ |
  35. \ |
  36. \ |
  37. \ |
  38.  
  39. """
  40.  
  41. """
  42. Definition for a undirected graph node
  43. """
  44. class UndirectedGraphNode:
  45. def __init__(self, x):
  46. self.label = x
  47. self.neighbors = []
  48.  
  49. """
  50. @param: node: A undirected graph node
  51. @return: A undirected graph node
  52. """
  53. class Solution:
  54.  
  55. def cloneGraph(self, node):
  56. if node==None:
  57. return node
  58. root = node
  59. nodes=[]
  60. q={node}
  61. while q:
  62. cur = q.pop()
  63. nodes.append(cur)
  64. for i in cur.neighbors:
  65. if i not in nodes:
  66. q.add(i)
  67. # print(nodes)
  68. map=dict()
  69. for n in nodes:
  70. map[n]=UndirectedGraphNode(n.label)
  71.  
  72. for n in nodes:
  73. temp = map[n]
  74. for ner in n.neighbors:
  75. temp.neighbors.append(map[ner])
  76.  
  77. return map[root]
  78. if __name__=="__main__":
  79. node = UndirectedGraphNode()
  80. node.neighbors.append(UndirectedGraphNode())
  81. node.neighbors.append(UndirectedGraphNode())
  82. s = Solution()
  83. print(s.cloneGraph(node))

137

 127. Topological Sorting

Description

Given an directed graph, a topological order of the graph nodes is defined as follow:
        For each directed edge A -> B in graph, A must before B in the order list.
        The first node in the order can be any node in the graph with no nodes direct to it.

Clarification:

{1,2,4#2,1,4#3,5#4,1,2#5,3} represents follow graph:

1------2  3
     \     |  |
      \    |  |
       \   |  |
        \  |  |
          4   5

we use # to split each node information.
    1,2,4 represents that 2, 4 are 1's neighbors
    2,1,4 represents that 1, 4 are 2's neighbors
    3,5 represents that 5 is 3's neighbor
    4,1,2 represents that 1, 2 are 4's neighbors
    5,3 represents that 3 is 5's neighbor
    
The topological order can be:

[0, 1, 2, 3, 4, 5]
    [0, 2, 3, 1, 5, 4]
    ...

Challenge
    Can you do it in both BFS and DFS?

  1. #coding:utf
  2. """
  3. . Topological Sorting
  4.  
  5. Description
  6.  
  7. Given an directed graph, a topological order of the graph nodes is defined as follow:
  8. For each directed edge A -> B in graph, A must before B in the order list.
  9. The first node in the order can be any node in the graph with no nodes direct to it.
  10.  
  11. Clarification:
  12.  
  13. {,,#,,#,#,,#,} represents follow graph:
  14.  
  15. ------
  16. \ | |
  17. \ | |
  18. \ | |
  19. \ | |
  20.  
  21. we use # to split each node information.
  22. ,, represents that , are 's neighbors
  23. ,, represents that , are 's neighbors
  24. , represents that is 's neighbor
  25. ,, represents that , are 's neighbors
  26. , represents that is 's neighbor
  27.  
  28. The topological order can be:
  29.  
  30. [, , , , , ]
  31. [, , , , , ]
  32. ...
  33.  
  34. Challenge
  35. Can you do it in both BFS and DFS?
  36.  
  37. """
  38.  
  39. """
  40. Definition for a Directed graph node
  41. class DirectedGraphNode:
  42. def __init__(self, x):
  43. self.label = x
  44. self.neighbors = []
  45. """
  46.  
  47. class Solution:
  48. """
  49. @param: graph: A list of Directed graph node
  50. @return: Any topological order for the given graph.
  51. """
  52. def topSort(self, graph):
  53. # write your code here
  54. if len(graph)==:
  55. return graph
  56. degree=dict()
  57. seen=set()
  58. for node in graph:
  59. if node not in seen:
  60. seen.add(node)
  61. if node not in degree:
  62. degree[node]=
  63. for nb in node.neighbors:
  64. if nb not in degree:
  65. degree[nb]=
  66. else:
  67. degree[nb]+=
  68. order=[]
  69. while seen:
  70. node =seen.pop()
  71. if degree[node]==:
  72. order.append(node)
  73. for nb in node.neighbors:
  74. degree[nb]-=
  75. else:
  76. seen.add(node)
  77. return order

127

7. Serialize and Deserialize Binary Tree

Description

Design an algorithm and write code to serialize and deserialize a binary tree.
    Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'.

There is no limit of how you deserialize or serialize a binary tree,
    LintCode will take your output of serialize as the input of deserialize, it won't check the result of serialize.

Example 1:

Input:{3,9,20,#,#,15,7}
    Output:{3,9,20,#,#,15,7}
    Explanation:
    Binary tree {3,9,20,#,#,15,7},  denote the following structure:
          3
         / \
        9  20
          /  \
         15   7
    it will be serialized {3,9,20,#,#,15,7}

Example 2:

Input:{1,2,3}
    Output:{1,2,3}
    Explanation:
    Binary tree {1,2,3},  denote the following structure:
       1
      / \
     2   3
    it will be serialized {1,2,3}

Our data serialization use BFS traversal. This is just for when you got Wrong Answer and want to debug the input.

You can use other method to do serializaiton and deserialization.

  1. #coding:utf-
  2.  
  3. """
  4. . Serialize and Deserialize Binary Tree
  5. Description
  6.  
  7. Design an algorithm and write code to serialize and deserialize a binary tree.
  8. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'.
  9.  
  10. There is no limit of how you deserialize or serialize a binary tree,
  11. LintCode will take your output of serialize as the input of deserialize, it won't check the result of serialize.
  12.  
  13. Example :
  14.  
  15. Input:{,,,#,#,,}
  16. Output:{,,,#,#,,}
  17. Explanation:
  18. Binary tree {,,,#,#,,}, denote the following structure:
  19.  
  20. / \
  21.  
  22. / \
  23.  
  24. it will be serialized {,,,#,#,,}
  25.  
  26. Example :
  27.  
  28. Input:{,,}
  29. Output:{,,}
  30. Explanation:
  31. Binary tree {,,}, denote the following structure:
  32.  
  33. / \
  34.  
  35. it will be serialized {,,}
  36.  
  37. Our data serialization use BFS traversal. This is just for when you got Wrong Answer and want to debug the input.
  38.  
  39. You can use other method to do serializaiton and deserialization.
  40.  
  41. """
  42.  
  43. """
  44. Definition of TreeNode:
  45. class TreeNode:
  46. def __init__(self, val):
  47. self.val = val
  48. self.left, self.right = None, None
  49. """
  50.  
  51. class Solution:
  52. """
  53. @param root: An object of TreeNode, denote the root of the binary tree.
  54. This method will be invoked first, you should design your own algorithm
  55. to serialize a binary tree which denote by a root node to a string which
  56. can be easily deserialized by your own "deserialize" method later.
  57. """
  58. def serialize(self, root):
  59. # write your code here
  60. if root==None:
  61. return root
  62. ret=[root.val]
  63. q=[root]
  64. while q:
  65. cur = q.pop()
  66. if cur.left!=None:
  67. q.append(cur.left)
  68. ret.append(cur.left.val)
  69. else:
  70. ret.append("#")
  71. if cur.right!=None:
  72. q.append(cur.right)
  73. ret.append(cur.right.val)
  74. else:
  75. ret.append("#")
  76. return ret
  77.  
  78. """
  79. @param data: A string serialized by your serialize method.
  80. This method will be invoked second, the argument data is what exactly
  81. you serialized at method "serialize", that means the data is not given by
  82. system, it's given by your own serialize method. So the format of data is
  83. designed by yourself, and deserialize it here as you serialize it in
  84. "serialize" method.
  85. """
  86. def deserialize(self, data):
  87. # write your code here
  88. if data==None or len(data)==:
  89. return None
  90.  
  91. root = TreeNode(data[])
  92. length=len(data)
  93. q=[root]
  94. i=
  95. while i<length and q:
  96. node = q.pop()
  97. if data[i]!="#":
  98. node.left = TreeNode(data[i])
  99. q.append(node.left)
  100. else:
  101. node.left=None
  102. if i+<length and data[i+]!="#" :
  103. node.right = TreeNode(data[i+])
  104. q.append(node.right)
  105. else:
  106. node.right=None
  107. i+=
  108. return root

7

120. Word Ladder

Description
    Given two words (start and end), and a dictionary, find the shortest transformation sequence from start to end, output the length of the sequence.
    Transformation rule such that:

Only one letter can be changed at a time
        Each intermediate word must exist in the dictionary. (Start and end words do not need to appear in the dictionary )

Return 0 if there is no such transformation sequence.
        All words have the same length.
        All words contain only lowercase alphabetic characters.
        You may assume no duplicates in the word list.
        You may assume beginWord and endWord are non-empty and are not the same.

Example 1:
    Input:start = "a",end = "c",dict =["a","b","c"]
    Output:2
    Explanation:
    "a"->"c"

Example 2:
    Input:start ="hit",end = "cog",dict =["hot","dot","dog","lot","log"]
    Output:5
    Explanation:
    "hit"->"hot"->"dot"->"dog"->"cog"

  1. #coding:utf-
  2.  
  3. """
  4. . Word Ladder
  5. Description
  6. Given two words (start and end), and a dictionary, find the shortest transformation sequence from start to end, output the length of the sequence.
  7. Transformation rule such that:
  8.  
  9. Only one letter can be changed at a time
  10. Each intermediate word must exist in the dictionary. (Start and end words do not need to appear in the dictionary )
  11.  
  12. Return if there is no such transformation sequence.
  13. All words have the same length.
  14. All words contain only lowercase alphabetic characters.
  15. You may assume no duplicates in the word list.
  16. You may assume beginWord and endWord are non-empty and are not the same.
  17.  
  18. Example :
  19. Input:start = "a",end = "c",dict =["a","b","c"]
  20. Output:
  21. Explanation:
  22. "a"->"c"
  23.  
  24. Example :
  25. Input:start ="hit",end = "cog",dict =["hot","dot","dog","lot","log"]
  26. Output:
  27. Explanation:
  28. "hit"->"hot"->"dot"->"dog"->"cog"
  29.  
  30. """
  31. #参考:https://leetcode-cn.com/problems/word-ladder/solution/dan-ci-jie-long-by-leetcode/
  32.  
  33. class Solution:
  34. """
  35. @param: start: a string
  36. @param: end: a string
  37. @param: dict: a set of string
  38. @return: An integer
  39. """
  40. def ladderLength(self, start, end, dict):
  41. # write your code here
  42. if (not start) or (not end) or len(dict)==:
  43. return
  44.  
  45. #构建图
  46. from collections import defaultdict
  47. graph = defaultdict(list)
  48. if start not in dict:
  49. dict.add(start)
  50. if end not in dict:
  51. dict.add(end)
  52. for word in dict:
  53. for i in range(len(word)):
  54. graph[word[:i]+"*"+word[i+:]].append(word)
  55.  
  56. q=[(start,)]
  57. seen=set()
  58. #Breadth first search
  59. while q:
  60. cur,level = q.pop()
  61.  
  62. for i in range(len(cur)):
  63. temp = cur[:i]+"*"+cur[i+:]
  64. for ner in graph[temp]:
  65. if ner==end:
  66. return level+
  67. if ner not in seen:
  68. q.append((ner,level+))
  69. seen.add(ner)
  70. # graph[temp]=[]
  71. return
  72.  
  73. # class Solution:
  74. # """
  75. # @param: start: a string
  76. # @param: end: a string
  77. # @param: dict: a set of string
  78. # @return: An integer
  79. # """
  80. # def ladderLength(self, start, end, dict):
  81. # # write your code here
  82. # if (not start) or (not end) or len(dict)==:
  83. # return
  84.  
  85. # #构建图
  86. # from collections import defaultdict
  87. # graph = defaultdict(list)
  88. # if start not in dict:
  89. # dict.append(start)
  90. # if end not in dict:
  91. # dict.append(end)
  92. # for i in dict:
  93. # for j in dict:
  94. # if i!=j and change_one(i,j):
  95. # graph[i].append(j)
  96.  
  97. # q=[(start,)]
  98. # seen=set()
  99. # order=[]
  100. # #Breadth first search
  101. # while q:
  102. # cur,level = q.pop()
  103. # for word in graph[cur]:
  104. # if word==end:
  105. # return level+
  106. # if word not in seen:
  107. # q.append((word,level+))
  108. # seen.add(word)
  109. # return
  110.  
  111. # def change_one(i,j):
  112. # length=len(i)
  113. # for n in range(length):
  114. # if i[:n]==j[:n] and i[n+:]==j[n+:]:
  115. # return True
  116.  
  117. if __name__=="__main__":
  118. s = Solution()
  119. print(s.ladderLength(start = "a",end = "c",dict ={"a","b","c"}))
  120. print(s.ladderLength(start ="hit",end = "cog",dict ={"hot","dot","dog","lot","log"}))

120

(五).  二叉树问题(Binary tree problem)

900. Closest Binary Search Tree Value

Description:

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
    Given target value is a floating point.
    You are guaranteed to have only one unique value in the BST that is closest to the target.

Example1
    Input: root = {5,4,9,2,#,8,10} and target = 6.124780
    Output: 5
    Explanation:
    Binary tree {5,4,9,2,#,8,10},  denote the following structure:
            5
           / \
         4    9
        /    / \
       2    8  10

Example2
    Input: root = {3,2,4,1} and target = 4.142857
    Output: 4
    Explanation:
    Binary tree {3,2,4,1},  denote the following structure:
         3
        / \
      2    4
     /
    1

  1. #coding:utf-
  2.  
  3. """
  4. . Closest Binary Search Tree Value
  5.  
  6. Description:
  7.  
  8. Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
  9. Given target value is a floating point.
  10. You are guaranteed to have only one unique value in the BST that is closest to the target.
  11.  
  12. Example1
  13. Input: root = {,,,,#,,} and target = 6.124780
  14. Output:
  15. Explanation:
  16. Binary tree {,,,,#,,}, denote the following structure:
  17.  
  18. / \
  19.  
  20. / / \
  21.  
  22. Example2
  23. Input: root = {,,,} and target = 4.142857
  24. Output:
  25. Explanation:
  26. Binary tree {,,,}, denote the following structure:
  27.  
  28. / \
  29.  
  30. /
  31.  
  32. """
  33.  
  34. """
  35. Definition of TreeNode:
  36. class TreeNode:
  37. def __init__(self, val):
  38. self.val = val
  39. self.left, self.right = None, None
  40. """
  41.  
  42. """
  43. Definition of TreeNode:
  44. class TreeNode:
  45. def __init__(self, val):
  46. self.val = val
  47. self.left, self.right = None, None
  48. """
  49.  
  50. class Solution:
  51. """
  52. @param root: the given BST
  53. @param target: the given target
  54. @return: the value in the BST that is closest to the target
  55. """
  56. def closestValue(self, root, target):
  57. # write your code here
  58.  
  59. if root==None or target==None:
  60. return None
  61.  
  62. ret,dif =root.val,abs(root.val-target)
  63. q=[root]
  64. while q:
  65. cur = q.pop()
  66. temp=abs(cur.val-target)
  67. if temp<dif:
  68. dif=temp
  69. ret = cur.val
  70. if cur.left !=None:
  71. q.append(cur.left)
  72. if cur.right !=None:
  73. q.append(cur.right)
  74. return ret

900

596. Minimum Subtree

Description

Given a binary tree, find the subtree with minimum sum. Return the root of the subtree.

LintCode will print the subtree which root is your return node.
    It's guaranteed that there is only one subtree with minimum sum and the given binary tree is not an empty tree.

Example 1:

Input:
    {1,-5,2,1,2,-4,-5}
    Output:1
    Explanation:
    The tree is look like this:
         1
       /   \
     -5     2
     / \   /  \
    1   2 -4  -5
    The sum of whole tree is minimum, so return the root.

Example 2:

Input:
    {1}
    Output:1
    Explanation:
    The tree is look like this:
       1
    There is one and only one subtree in the tree. So we return 1.

  1. #coding:utf-
  2.  
  3. #https://www.lintcode.com/problem/minimum-subtree/description
  4. """
  5. . Minimum Subtree
  6.  
  7. Description
  8.  
  9. Given a binary tree, find the subtree with minimum sum. Return the root of the subtree.
  10.  
  11. LintCode will print the subtree which root is your return node.
  12. It's guaranteed that there is only one subtree with minimum sum and the given binary tree is not an empty tree.
  13.  
  14. Example :
  15.  
  16. Input:
  17. {,-,,,,-,-}
  18. Output:
  19. Explanation:
  20. The tree is look like this:
  21.  
  22. / \
  23. -
  24. / \ / \
  25. - -
  26. The sum of whole tree is minimum, so return the root.
  27.  
  28. Example :
  29.  
  30. Input:
  31. {}
  32. Output:
  33. Explanation:
  34. The tree is look like this:
  35.  
  36. There is one and only one subtree in the tree. So we return .
  37.  
  38. """
  39.  
  40. #Definition of TreeNode:
  41. class TreeNode:
  42. def __init__(self, val):
  43. self.val = val
  44. self.left, self.right = None, None
  45.  
  46. class Solution:
  47. """
  48. @param root: the root of binary tree
  49. @return: the root of the minimum subtree
  50. """
  51. import sys
  52. def __init__(self):
  53. self.ret=None
  54. self.minimum=sys.maxsize
  55. def findSubtree(self, root):
  56. # write your code here
  57. if root==None:
  58. return root
  59. self.cal_min_sum(root)
  60. # print(Solution.ret.val)
  61. return self.ret
  62.  
  63. def cal_min_sum(self,node):
  64. if node==None:
  65. return
  66. temp = node.val+self.cal_min_sum(node.left)+self.cal_min_sum(node.right)
  67. if temp<self.minimum:
  68. self.minimum=temp
  69. self.ret=node
  70. return temp #必须得返回
  71.  
  72. if __name__=="__main__":
  73.  
  74. s = Solution()
  75. # root = TreeNode()
  76. # root.left,root.right=TreeNode(-),TreeNode()
  77. # root.left.left,root.left.right = TreeNode(),TreeNode()
  78. # root.right.left,root.right.right = TreeNode(-),TreeNode(-)
  79. root = TreeNode()
  80. root.right=TreeNode()
  81. print(s.findSubtree(root))

596

480 Binary Tree Pathss

Description

Given a binary tree, return all root-to-leaf paths.

Example 1:

Input:{1,2,3,#,5}
    Output:["1->2->5","1->3"]
    Explanation:
       1
     /   \
    2     3
     \
      5

Example 2:

Input:{1,2}
    Output:["1->2"]
    Explanation:
       1
     /   
    2

  1. #coding:utf-
  2.  
  3. """
  4. Binary Tree Pathss
  5. Description
  6.  
  7. Given a binary tree, return all root-to-leaf paths.
  8.  
  9. Example :
  10.  
  11. Input:{,,,#,}
  12. Output:["1->2->5","1->3"]
  13. Explanation:
  14.  
  15. / \
  16.  
  17. \
  18.  
  19. Example :
  20.  
  21. Input:{,}
  22. Output:["1->2"]
  23. Explanation:
  24.  
  25. /
  26.  
  27. """
  28.  
  29. """
  30. Definition of TreeNode:
  31. class TreeNode:
  32. def __init__(self, val):
  33. self.val = val
  34. self.left, self.right = None, None
  35. """
  36. """
  37. Definition of TreeNode:
  38. class TreeNode:
  39. def __init__(self, val):
  40. self.val = val
  41. self.left, self.right = None, None
  42. """
  43.  
  44. class Solution:
  45. """
  46. @param root: the root of the binary tree
  47. @return: all root-to-leaf paths
  48. """
  49. def binaryTreePaths(self, root):
  50. # write your code here
  51. if root==None:
  52. return []
  53. paths=[]
  54. self.helper(root,paths,"")
  55. return paths
  56.  
  57. def helper(self,node,paths,tree):
  58. if node.left==None and node.right==None:
  59. paths.append(tree+str(node.val))
  60. if node.left!=None:
  61. self.helper(node.left,paths,tree+str(node.val)+"->")
  62. if node.right!=None:
  63. self.helper(node.right,paths,tree+str(node.val)+"->")

480

453. Flatten Binary Tree to Linked List

Description
    Flatten a binary tree to a fake "linked list" in pre-order traversal.
    Here we use the right pointer in TreeNode as the next pointer in ListNode.
    Don't forget to mark the left child of each node to null. Or you will get Time Limit Exceeded or Memory Limit Exceeded.

Example 1:

Input:{1,2,5,3,4,#,6}
    Output:{1,#,2,#,3,#,4,#,5,#,6}
    Explanation:
         1
        / \
       2   5
      / \   \
     3   4   6

1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6

Example 2:

Input:{1}
    Output:{1}
    Explanation:
             1
             1

Challenge
    Do it in-place without any extra memory.

  1. #coding:utf-
  2.  
  3. """
  4. . Flatten Binary Tree to Linked List
  5.  
  6. Description
  7. Flatten a binary tree to a fake "linked list" in pre-order traversal.
  8. Here we use the right pointer in TreeNode as the next pointer in ListNode.
  9. Don't forget to mark the left child of each node to null. Or you will get Time Limit Exceeded or Memory Limit Exceeded.
  10.  
  11. Example :
  12.  
  13. Input:{,,,,,#,}
  14. Output:{,#,,#,,#,,#,,#,}
  15. Explanation:
  16.  
  17. / \
  18.  
  19. / \ \
  20.  
  21. \
  22.  
  23. \
  24.  
  25. \
  26.  
  27. \
  28.  
  29. \
  30.  
  31. Example :
  32.  
  33. Input:{}
  34. Output:{}
  35. Explanation:
  36.  
  37. Challenge
  38. Do it in-place without any extra memory.
  39.  
  40. """
  41. #参考:https://blog.csdn.net/c070363/article/details/51203408
  42.  
  43. """
  44. Definition of TreeNode:
  45. class TreeNode:
  46. def __init__(self, val):
  47. self.val = val
  48. self.left, self.right = None, None
  49. """
  50.  
  51. class Solution:
  52. """
  53. @param root: a TreeNode, the root of the binary tree
  54. @return: nothing
  55. """
  56. def flatten(self, root):
  57. # write your code here
  58. node = root
  59. while node:
  60. if node.left!=None:
  61. temp = node.left
  62. while temp.right:
  63. temp = temp.right
  64. temp.right = node.right
  65. node.right = node.left
  66. node.left=None
  67. node = node.right
  68. return root

453

 

93. Balanced Binary Tree
Description

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.

Example  1:
    Input: tree = {1,2,3}
    Output: true
    
    Explanation:
    This is a balanced binary tree.
          1  
         / \                
        2  3

Example  2:
    Input: tree = {3,9,20,#,#,15,7}
    Output: true
    
    Explanation:
    This is a balanced binary tree.
          3  
         / \                
        9  20                
          /  \                
         15   7

Example  3:
    Input: tree = {1,#,2,3,4}
    Output: false
    
    Explanation:
    This is not a balanced tree.
    The height of node 1's right sub-tree is 2 but left sub-tree is 0.
          1  
           \                
           2                
          /  \                
         3   4

  1. #coding:utf-
  2.  
  3. """
  4. . Balanced Binary Tree
  5. Description
  6.  
  7. Given a binary tree, determine if it is height-balanced.
  8. 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 .
  9.  
  10. Example :
  11. Input: tree = {,,}
  12. Output: true
  13.  
  14. Explanation:
  15. This is a balanced binary tree.
  16.  
  17. / \
  18.  
  19. Example :
  20. Input: tree = {,,,#,#,,}
  21. Output: true
  22.  
  23. Explanation:
  24. This is a balanced binary tree.
  25.  
  26. / \
  27.  
  28. / \
  29.  
  30. Example :
  31. Input: tree = {,#,,,}
  32. Output: false
  33.  
  34. Explanation:
  35. This is not a balanced tree.
  36. The height of node 's right sub-tree is 2 but left sub-tree is 0.
  37.  
  38. \
  39.  
  40. / \
  41.  
  42. """
  43. #参考:https://www.jiuzhang.com/solutions/balanced-binary-tree/#tag-highlight-lang-python
  44.  
  45. """
  46. Definition of TreeNode:
  47. class TreeNode:
  48. def __init__(self, val):
  49. self.val = val
  50. self.left, self.right = None, None
  51. """
  52.  
  53. class Solution:
  54. """
  55. @param root: The root of binary tree.
  56. @return: True if this Binary tree is Balanced, or false.
  57. """
  58. def isBalanced(self, root):
  59. # write your code here
  60.  
  61. balanced,_ = self.cal_balance(root)
  62. return balanced
  63.  
  64. def cal_balance(self,node):
  65. if node==None:
  66. return True,
  67. balanced,leftHeight = self.cal_balance(node.left)
  68. if not balanced:
  69. return False,
  70. balanced,rightHeight = self.cal_balance(node.right)
  71. if not balanced:
  72. return False,
  73. dif = abs(leftHeight-rightHeight)
  74. return dif<=,max(leftHeight,rightHeight)+

93

902. Kth Smallest Element in a BST
Description
    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

Example 1:

Input:{1,#,2},2
    Output:2
    Explanation:
        1
         \
          2
    The second smallest element is 2.

Example 2:

Input:{2,1,3},1
    Output:1
    Explanation:
      2
     / \
    1   3
    The first smallest element is 1.

Challenge

What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

  1. #coding:utf-
  2. """
  3. . Kth Smallest Element in a BST
  4. Description
  5. Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
  6.  
  7. You may assume k is always valid, ≤ k ≤ BST's total elements.
  8.  
  9. Example :
  10.  
  11. Input:{,#,},
  12. Output:
  13. Explanation:
  14.  
  15. \
  16.  
  17. The second smallest element is .
  18.  
  19. Example :
  20.  
  21. Input:{,,},
  22. Output:
  23. Explanation:
  24.  
  25. / \
  26.  
  27. The first smallest element is .
  28.  
  29. Challenge
  30.  
  31. What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
  32.  
  33. """
  34.  
  35. """
  36. Definition of TreeNode:
  37. class TreeNode:
  38. def __init__(self, val):
  39. self.val = val
  40. self.left, self.right = None, None
  41. """
  42.  
  43. class Solution:
  44. """
  45. @param root: the given BST
  46. @param k: the given k
  47. @return: the kth smallest element in BST
  48. """
  49. def kthSmallest(self, root, k):
  50. # write your code here
  51. if root==None:
  52. return None
  53. vals=[]
  54. self.findElement(root,vals)
  55. return vals[k-]
  56.  
  57. def findElement(self,node,vals):
  58. if node==None:
  59. return
  60. self.findElement(node.left,vals)
  61. vals.append(node.val)
  62. self.findElement(node.right,vals)

902

578. Lowest Common Ancestor III
Description

Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.
    The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.
    Return null if LCA does not exist.

node A or node B may not exist in tree.

Example1

Input:
    {4, 3, 7, #, #, 5, 6}
    3 5
    5 6
    6 7
    5 8
    Output:
    4
    7
    7
    null
    Explanation:
      4
     / \
    3   7
       / \
      5   6

LCA(3, 5) = 4
    LCA(5, 6) = 7
    LCA(6, 7) = 7
    LCA(5, 8) = null

Example2

Input:
    {1}
    1 1
    Output:
    1
    Explanation:
    The tree is just a node, whose value is 1.

  1. #coding:utf-
  2. """
  3. . Lowest Common Ancestor III
  4. Description
  5.  
  6. Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.
  7. The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.
  8. Return null if LCA does not exist.
  9.  
  10. node A or node B may not exist in tree.
  11.  
  12. Example1
  13.  
  14. Input:
  15. {, , , #, #, , }
  16.  
  17. Output:
  18.  
  19. null
  20. Explanation:
  21.  
  22. / \
  23.  
  24. / \
  25.  
  26. LCA(, ) =
  27. LCA(, ) =
  28. LCA(, ) =
  29. LCA(, ) = null
  30.  
  31. Example2
  32.  
  33. Input:
  34. {}
  35.  
  36. Output:
  37.  
  38. Explanation:
  39. The tree is just a node, whose value is .
  40.  
  41. """
  42.  
  43. """
  44. Definition of TreeNode:
  45. class TreeNode:
  46. def __init__(self, val):
  47. this.val = val
  48. this.left, this.right = None, None
  49. """
  50.  
  51. class Solution:
  52. """
  53. @param: root: The root of the binary tree.
  54. @param: A: A TreeNode
  55. @param: B: A TreeNode
  56. @return: Return the LCA of the two nodes.
  57. """
  58. def lowestCommonAncestor3(self, root, A, B):
  59. # write your code here
  60. if root==None:
  61. return root
  62. foundA,foundB,ret=self.helper(root,A,B)
  63. if foundA and foundB:
  64. return ret
  65.  
  66. def helper(self,node,A,B):
  67. if node==None:
  68. return False,False,None
  69. leftA,leftB,ret=self.helper(node.left,A,B)
  70. if leftA and leftB:
  71. return leftA,leftB,ret
  72. rightA,rightB,ret=self.helper(node.right,A,B)
  73. if rightA and rightB:
  74. return rightA,rightB,ret
  75.  
  76. foundA = leftA or rightA
  77. foundB = leftB or rightB
  78. if foundA and foundB:
  79. return True,True,node
  80. if foundA==True:
  81. return True,node==B,node
  82. if foundB==True:
  83. return node==A,True,node
  84. return node==A, node==B, node

578

95. Validate Binary Search Tree
Description

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node's key.
        The right subtree of a node contains only nodes with keys greater than the node's key.
        Both the left and right subtrees must also be binary search trees.
        A single node tree is a BST

Example 1:

Input:  {-1}
    Output:true
    Explanation:
    For the following binary tree(only one node):
              -1
    This is a binary search tree.

Example 2:

Input:  {2,1,4,#,#,3,5}
    Output: true
    For the following binary tree:
          2
         / \
        1   4
           / \
          3   5
    This is a binary search tree.

  1. . Validate Binary Search Tree
  2. Description
  3.  
  4. Given a binary tree, determine if it is a valid binary search tree (BST).
  5.  
  6. Assume a BST is defined as follows:
  7.  
  8. The left subtree of a node contains only nodes with keys less than the node's key.
  9. The right subtree of a node contains only nodes with keys greater than the node's key.
  10. Both the left and right subtrees must also be binary search trees.
  11. A single node tree is a BST
  12.  
  13. Example :
  14.  
  15. Input: {-}
  16. Outputtrue
  17. Explanation
  18. For the following binary treeonly one node):
  19. -
  20. This is a binary search tree.
  21.  
  22. Example :
  23.  
  24. Input: {,,,#,#,,}
  25. Output: true
  26. For the following binary tree:
  27.  
  28. / \
  29.  
  30. / \
  31.  
  32. This is a binary search tree.

95

 

901. Closest Binary Search Tree Value II

Description
    Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.

Given target value is a floating point.
        You may assume k is always valid, that is: k ≤ total nodes.
        You are guaranteed to have only one unique set of k values in the BST that are closest to the target.

Example 1:

Input:
    {1}
    0.000000
    1
    Output:
    [1]
    Explanation:
    Binary tree {1},  denote the following structure:
     1

Example 2:

Input:
    {3,1,4,#,2}
    0.275000
    2
    Output:
    [1,2]
    Explanation:
    Binary tree {3,1,4,#,2},  denote the following structure:
      3
     /  \
    1    4
     \
      2

Challenge
    Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?

  1. #coding:utf-
  2. """
  3. . Closest Binary Search Tree Value II
  4.  
  5. Description
  6. Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.
  7.  
  8. Given target value is a floating point.
  9. You may assume k is always valid, that is: k ≤ total nodes.
  10. You are guaranteed to have only one unique set of k values in the BST that are closest to the target.
  11.  
  12. Example :
  13.  
  14. Input:
  15. {}
  16. 0.000000
  17.  
  18. Output:
  19. []
  20. Explanation:
  21. Binary tree {}, denote the following structure:
  22.  
  23. Example :
  24.  
  25. Input:
  26. {,,,#,}
  27. 0.275000
  28.  
  29. Output:
  30. [,]
  31. Explanation:
  32. Binary tree {,,,#,}, denote the following structure:
  33.  
  34. / \
  35.  
  36. \
  37.  
  38. Challenge
  39.  
  40. Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?
  41. """
  42. #参考:https://www.jiuzhang.com/solution/closest-binary-search-tree-value-ii/#tag-highlight-lang-python
  43. #一次中序遍历得到排序链表,顺便记录一下最接近的数,接着用双指针从最接近的数向两边搜索,加入结果链表。
  44.  
  45. """
  46. Definition of TreeNode:
  47. class TreeNode:
  48. def __init__(self, val):
  49. self.val = val
  50. self.left, self.right = None, None
  51. """
  52.  
  53. class Solution:
  54. """
  55. @param root: the given BST
  56. @param target: the given target
  57. @param k: the given k
  58. @return: k values in the BST that are closest to the target
  59. """
  60. def closestKValues(self, root, target, k):
  61. # write your code here
  62.  
  63. ret =[]
  64. if root==None:
  65. return ret
  66. import sys
  67. self.nearest = None
  68. self.dif=sys.maxsize
  69. self.helper(root,target,ret)
  70. i=j=ret.index(self.nearest)
  71. temp=[ret[i]]
  72. k-=
  73. while k> and i> and j<len(ret)-:
  74. if abs(ret[i-]-target)<=abs(ret[j+]-target):
  75. i-=
  76. temp.append(ret[i])
  77. else:
  78. j+=
  79. temp.append(ret[j])
  80. k-=
  81. if k>:
  82. if i==:
  83. temp.extend(ret[j+:j+k+])
  84. else:
  85. temp.extend(ret[i-k:i])
  86. return temp
  87.  
  88. def helper(self,node,target,ret):
  89. if node==None:
  90. return
  91. if node.left:
  92. self.helper(node.left,target,ret)
  93. if abs(node.val-target)<self.dif:
  94. self.dif = abs(node.val-target)
  95. self.nearest=node.val
  96. ret.append(node.val)
  97. if node.right:
  98. self.helper(node.right,target,ret)

901

86. Binary Search Tree Iterator

description

Design an iterator over a binary search tree with the following rules:

Elements are visited in ascending order (i.e. an in-order traversal)
        next() and hasNext() queries run in O(1) time in average.

Example 1

Input:  {10,1,11,#,6,#,12}
    Output:  [1, 6, 10, 11, 12]
    Explanation:
    The BST is look like this:
      10
      /\
     1 11
      \  \
       6  12
    You can return the inorder traversal of a BST [1, 6, 10, 11, 12]

Example 2

Input: {2,1,3}
    Output: [1,2,3]
    Explanation:
    The BST is look like this:
      2
     / \
    1   3
    You can return the inorder traversal of a BST tree [1,2,3]

Challenge

Extra memory usage O(h), h is the height of the tree.
    Super Star: Extra memory usage O(1)

  1. #coding:utf-
  2. """
  3. . Binary Search Tree Iterator
  4. description
  5.  
  6. Design an iterator over a binary search tree with the following rules:
  7.  
  8. Elements are visited in ascending order (i.e. an in-order traversal)
  9. next() and hasNext() queries run in O() time in average.
  10.  
  11. Example
  12.  
  13. Input: {,,,#,,#,}
  14. Output: [, , , , ]
  15. Explanation:
  16. The BST is look like this:
  17.  
  18. /\
  19.  
  20. \ \
  21.  
  22. You can return the inorder traversal of a BST [, , , , ]
  23.  
  24. Example
  25.  
  26. Input: {,,}
  27. Output: [,,]
  28. Explanation:
  29. The BST is look like this:
  30.  
  31. / \
  32.  
  33. You can return the inorder traversal of a BST tree [,,]
  34.  
  35. Challenge
  36.  
  37. Extra memory usage O(h), h is the height of the tree.
  38. Super Star: Extra memory usage O()
  39. """
  40.  
  41. """
  42. Definition of TreeNode:
  43. class TreeNode:
  44. def __init__(self, val):
  45. self.val = val
  46. self.left, self.right = None, None
  47.  
  48. Example of iterate a tree:
  49. iterator = BSTIterator(root)
  50. while iterator.hasNext():
  51. node = iterator.next()
  52. do something for node
  53. """
  54.  
  55. class BSTIterator:
  56. """
  57. @param: root: The root of binary tree.
  58. """
  59. def __init__(self, root):
  60. # do intialization if necessary
  61. self.ret =[]
  62. self.traverse(root)
  63. self.length=len(self.ret)
  64. self.k=
  65.  
  66. """
  67. @return: True if there has next node, or false
  68. """
  69. def hasNext(self, ):
  70. # write your code here
  71. if self.k<self.length:
  72. return True
  73.  
  74. """
  75. @return: return next node
  76. """
  77. def next(self, ):
  78. # write your code here
  79. temp = self.ret[self.k]
  80. self.k+=
  81. return temp
  82.  
  83. def traverse(self,root):
  84. if root==None:
  85. return
  86. if root.left:
  87. self.traverse(root.left)
  88. self.ret.append(root)
  89. if root.right:
  90. self.traverse(root.right)

86

详细代码可参见:https://github.com/silence-cho/cv-learning

lintcode刷题笔记(一)的更多相关文章

  1. LintCode刷题笔记-- LongestCommonSquence

    标签:动态规划 题目描述: Given two strings, find the longest common subsequence (LCS). Your code should return ...

  2. LintCode刷题笔记-- PaintHouse 1&2

    标签: 动态规划 题目描述: There are a row of n houses, each house can be painted with one of the k colors. The ...

  3. LintCode刷题笔记-- Maximum Product Subarray

    标签: 动态规划 描述: Find the contiguous subarray within an array (containing at least one number) which has ...

  4. LintCode刷题笔记-- Maximal Square

    标签:动态规划 题目描述: Given a 2D binary matrix filled with 0's and 1's, find the largest square containing a ...

  5. LintCode刷题笔记-- Edit distance

    标签:动态规划 描述: Given two words word1 and word2, find the minimum number of steps required to convert wo ...

  6. LintCode刷题笔记-- Distinct Subsequences

    标签:动态规划 题目描述: Given a string S and a string T, count the number of distinct subsequences of T in S. ...

  7. LintCode刷题笔记-- BackpackIV

    标签: 动态规划 描述: Given an integer array nums with all positive numbers and no duplicates, find the numbe ...

  8. LintCode刷题笔记-- BackpackII

    标记: 动态规划 问题描述: Given n items with size Ai, an integer m denotes the size of a backpack. How full you ...

  9. LintCode刷题笔记-- Update Bits

    标签: 位运算 描述: Given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set ...

随机推荐

  1. LNMP环境搭建wordpress博客及伪静态

    WordPress是使用PHP语言开发的博客平台,是一款开源的软件,用户可以在支持PHP和MySQL数据库的服务器上架设属于自己的网站.也可以把 WordPress当作一个内容管理系统(CMS)来使用 ...

  2. Django组件之用户认证

    auth模块 1 from django.contrib import auth django.contrib.auth中提供了许多方法,这里主要介绍其中的三个: 1.1 .authenticate( ...

  3. 【OF框架】缓存Session/Cookies/Cache代码调用api,切换缓存到Redis

    准备 缓存服务在应用开发中最常用的功能,特别是Session和Cookies,Cache部分业务开发过程会使用到. 在负载均衡环境下,缓存服务需要存储到服务器. 缓存默认实现在内存在,可以通过配置切换 ...

  4. Python 使用 docopt 解析json参数文件

    1. 背景 在深度学习的任务中,通常需要比较复杂的参数以及输入输出配置,比如需要不同的训练data,不同的模型,写入不同的log文件,输出到不同的文件夹以免混淆输出 常用的parser.add()方法 ...

  5. Nutch2.1+mysql+solr3.6.1+中文网站抓取

    1.mysql 数据库配置 linux mysql安装步骤省略. 在首先进入/etc/my.cnf (mysql为5.1的话就不用修改my.cnf,会导致mysql不能启动)在[mysqld] 下添加 ...

  6. 学到了林海峰,武沛齐讲的Day14完

    全局变量和局部变量 局部里面定义 global name    ======将局部变量变成全局变量 nonlocal name # nonlocal,指定上一级变量,如果没有就继续往上直到找到为止 有 ...

  7. 使用AJAX传输不了值时

    当时候AJAX往后台传递值时  传不到后台  这时我们就要检查程序是否有问题了 一般AJAX程序 $.ajax( { type: "POST", url: "Login. ...

  8. Linux系统出现hung_task_timeout_secs和blocked for more than 120 seconds的解决方法

    Linux系统出现系统没有响应. 在/var/log/message日志中出现大量的 “echo 0 > /proc/sys/kernel/hung_task_timeout_secs" ...

  9. bzoj 3629

    给出数 $n$记 $f(x)$ 表示 $x$ 的因子和求出所有 $x$ 使得 $f(x) = n$考虑 $x = p_1 ^{a_1} * p_2 ^ {a_2} * \cdots * p_k ^ { ...

  10. Educational Codeforces Round 68

    目录 Contest Info Solutions A.Remove a Progression B.Yet Another Crosses Problem C.From S To T D.1-2-K ...