lintcode刷题笔记(一)
最近开始刷lintcode,记录下自己的答案,数字即为lintcode题目号,语言为python3,坚持日拱一卒吧。。。
(一). 回文字符窜问题(Palindrome problem)
627. Longest Palindrome
给出一个包含大小写字母的字符串。求出由这些字母构成的最长的回文串的长度是多少。
数据是大小写敏感的,也就是说,"Aa"
并不会被认为是一个回文串
输入 : s = "abccccdd"
输出 : 7
说明 : 一种可以构建出来的最长回文串方案是 "dccaccd"。
- #coding:utf-
- class Solution:
- """
- @param s: a string which consists of lowercase or uppercase letters
- @return: the length of the longest palindromes that can be built
- """
- def longestPalindrome(self, s):
- # write your code here
- char_set=set()
- for c in s:
- if c in char_set:
- char_set.remove(c) #出现偶数次的字母去除掉,留下出现奇数次
- else:
- char_set.add(c)
- single_count = len(char_set)
- if single_count>:
- single_count = single_count- #留一个单字母在回文正中间
- return len(s)-single_count
- if __name__=="__main__":
- s = Solution()
- print(s.longestPalindrome("abccccdd"))
627
200. Longest Palindromic Substring
Description
给出一个字符串(假设长度最长为1000),求出它的最长回文子串,你可以假定只有一个满足条件的最长回文串。
Example
样例 1:
输入:"abcdzdcab"
输出:"cdzdc"
样例 2:
输入:"aba"
输出:"aba"
- #coding:utf-
- class Solution:
- def longestPalindrome(self, s):
- # write your code here
- length = len(s)
- sub="" if length> else s
- m =
- for i in range(length-):
- len1,sub1 = expandAroundCenter(s,m,i,i)
- len2,sub2 = expandAroundCenter(s,m,i,i+)
- if len1>m:
- m = len1
- sub = sub1
- if len2>m:
- m = len2
- sub = sub2
- return sub
- def expandAroundCenter(s,m,i,j):
- sub=""
- while i>= and j<=len(s)-:
- if s[i]==s[j]:
- if j-i+>m:
- m = j-i+
- sub = s[i:j+]
- i=i-
- j=j+
- else:
- break
- return m,sub
- if __name__=="__main__":
- s = Solution()
- print(s.longestPalindrome("abcdzdcab"))
- print(s.longestPalindrome("aba"))
- print(s.longestPalindrome("a"))
- print(s.longestPalindrome("ccc"))
- print(s.longestPalindrome("cc"))
- print(s.longestPalindrome("cccc"))
(二). 二分搜索法和log(n)算法(Binary Search & Log(n) Algorithm)
458. Last Position of Target
给一个升序数组,找到 target
最后一次出现的位置,如果没出现过返回 -1
样例 :
输入:nums = [1,2,2,4,5,5], target = 2
输出:2
输入:nums = [1,2,2,4,5,5], target = 6
输出:-1
- #coding:utf-
- class Solution:
- #获取最右边的
- def lastPosition(self, nums, target):
- start =
- end = len(nums)-
- index = -
- while start<=end:
- mid = (start+end)//
- if nums[mid]<=target:
- start = mid+
- elif nums[mid]>target:
- end = mid-
- if start> and nums[start-]==target:
- index = start-
- return index
- #获取最左边的
- def firstPosition(self, nums, target):
- start =
- end = len(nums)-
- index = -
- while start<=end:
- mid = (start+end)//
- if nums[mid]<target:
- start = mid+
- elif nums[mid]>=target:
- end = mid-
- if end<len(nums)- and nums[end+]==target:
- index = end+
- return index
- if __name__=="__main__":
- s = Solution()
- print(s.lastPosition(nums = [], target = ))
- print(s.lastPosition(nums = [,,,,,], target = ))
- print(s.lastPosition(nums = [,,,,,], target = ))
- print(s.lastPosition(nums = [,,,,,], target = ))
- print(s.firstPosition(nums = [,,,,,], target = ))
- print(s.firstPosition(nums = [,,,,,], target = ))
- print(s.firstPosition(nums = [,,,,,], target = ))
458
585. Maximum Number in Mountain Sequence
给 n
个整数的山脉数组,即先增后减的序列,找到山顶(最大值)
Example
例1:
输入: nums = [1, 2, 4, 8, 6, 3]
输出: 8
例2:
输入: nums = [10, 9, 8, 7],
输出: 10
- #coding:utf-
- class Solution:
- def mountainSequence(self, nums):
- # write your code here
- if len(nums)==:
- return nums[]
- for i in range(len(nums)-):
- if nums[i+]<nums[i]:
- return nums[i]
585
460. Find K Closest Elements
Description
给一个目标数 target
, 一个非负整数 k
, 一个按照升序排列的数组 A
。在A
中找与target
最接近的k
个整数。返回这k
个数并按照与target
的接近程度从小到大排序,如果接近程度相当,那么小的数排在前面。
k
是一个非负整数,并且总是小于已排序数组的长度。- 给定数组的长度是正整数, 不会超过 10^44
- 数组中元素的绝对值不会超过 10^44
Example
样例 1:
输入: A = [1, 2, 3], target = 2, k = 3
输出: [2, 1, 3]
样例 2:
输入: A = [1, 4, 6, 8], target = 3, k = 3
输出: [4, 1, 6]
- class Solution:
- """
- @param A: an integer array
- @param target: An integer
- @param k: An integer
- @return: an integer array
- """
- def kClosestNumbers(self, A, target, k):
- # write your code here
- sub=
- nearest=-
- start =
- end = len(A)-
- while start<=end:
- mid = (start+end)//
- temp = abs(A[mid]-target)
- if temp<sub:
- sub = temp
- nearest = mid
- if A[mid]>target:
- end = mid-
- elif A[mid]<target:
- start = mid+
- elif A[mid]==target:
- break
- out=[]
- if nearest!=- and k>:
- out.append(A[nearest])
- i=
- left,right=nearest-,nearest+
- while left>= and right<=len(A)- and i<k:
- if abs(A[left]-target)<=abs(A[right]-target):
- out.append(A[left])
- left = left-
- else:
- out.append(A[right])
- right = right+
- i = i+
- if i<k and left<:
- out.extend(A[right:right+k-i])
- if i<k and right>len(A)-:
- out.extend(A[left:left-(k-i):-])
- return out
- if __name__=="__main__":
- s = Solution()
- print(s.kClosestNumbers( A = [, , ], target = , k = ))
- print(s.kClosestNumbers(A = [, , , ], target = , k = ))
- print(s.kClosestNumbers(A = [,,,,], target = , k = ))
- print(s.kClosestNumbers(A = [,,,,,,,], target = , k = ))
- print(s.kClosestNumbers(A = [,,,,,,], target = , k = ))
- print(s.kClosestNumbers(A = [,,,], target = , k = ))
460
428. Pow(x,n)
实现 pow(x, n). (n是一个整数,不用担心精度,当答案和标准输出差绝对值小于1e-3
时都算正确)
Example
样例 1:
输入: x = 9.88023, n = 3
输出: 964.498
样例 2:
输入: x = 2.1, n = 3
输出: 9.261
样例 3:
输入: x = 1, n = 0
输出: 1
- #coding:utf-
- class Solution:
- def myPow(self,x,n):
- if n==:
- return
- elif n<:
- x = /x
- n = -n
- return recursive_pow(x,n)
- def recursive_pow(x,n):
- if n==:
- return x
- else:
- half = recursive_pow(x,n//2)
- if n%==:
- return half*half*x
- else:
- return half*half
- if __name__=="__main__":
- s = Solution()
- print(s.myPow(x = 9.88023, n = ))
- print(s.myPow(x = 2.1, n = ))
- print(s.myPow( x = , n = ))
- 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:
输入:[4, 5, 6, 7, 0, 1, 2]
输出:0
解释:
数组中的最小值为0
Example 2:
输入:[2,1]
输出:1
解释:
数组中的最小值为1
- #coding:utf-
- class Solution:
- def findMin(self, nums):
- length = len(nums)
- if length==:
- return nums[]
- elif length>:
- if nums[]<nums[-]:
- return nums[]
- else:
- left,right = ,length-
- while left<right:
- mid = (left+right)//
- if nums[mid]>nums[left]:
- left = mid
- elif nums[mid]<nums[left]:
- right = mid
- else: #mid和left相等时
- break
- return nums[right]
- if __name__=="__main__":
- s = Solution()
- print(s.findMin([, , , , , , ]))
- print(s.findMin([,]))
159
140. Fast Power
计算an % b,其中a,b和n都是32位的非负整数。
Example
例如 231 % 3 = 2
例如 1001000 % 1000 = 0
Challenge
O(logn)
- #coding:utf-
- #原理: (A*B)%p = ((A%p)*(B%p))%p
- """
- @param a: A 32bit integer
- @param b: A 32bit integer
- @param n: A 32bit integer
- @return: An integer
- """
- class Solution:
- def fastPower(self, a, b, n):
- if n==:
- return %b
- elif n==:
- return a%b
- else:
- half_remainder = self.fastPower(a,b,n//2)
- if n%==:
- return (half_remainder*half_remainder*a)%b
- else:
- return (half_remainder*half_remainder)%b
- if __name__=="__main__":
- s = Solution()
- print(s.fastPower(,,))
- print(s.fastPower(,,))
- 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, 3, 4, 5, 7, 6]
输出: 1 or 6
解释:
返回峰顶元素的下标
样例 2:
输入: [1,2,3,4,1]
输出: 3
- #coding:utf-
- #参考题解:https://leetcode-cn.com/problems/find-peak-element/solution/hua-jie-suan-fa-162-xun-zhao-feng-zhi-by-guanpengc/
- #注意峰值的方向,先上升后下降
- """
- @param A: An integers array.
- @return: return any of peek positions.
- """
- class Solution:
- def findPeak(self, A):
- # write your code here
- length = len(A)
- if length==:
- return
- elif length>:
- left,right = , length-
- while left<right:
- mid = (left+right)//
- if A[mid]>A[mid+]: #下降趋势
- right = mid
- elif A[mid]<A[mid+]: #上升趋势
- left = mid+
- return left
- if __name__=="__main__":
- s = Solution()
- print(s.findPeak([, , , , , , , ]))
- print(s.findPeak([,,,,]))
75
74. First Bad Version
代码库的版本号是从 1 到 n 的整数。某一天,有人提交了错误版本的代码,因此造成自身及之后版本的代码在单元测试中均出错。请找出第一个错误的版本号。
你可以通过 isBadVersion
的接口来判断版本号 version 是否在单元测试中出错,具体接口详情和调用方法请见代码的注释部分。
Example
n = 5:
isBadVersion(3) -> false
isBadVersion(5) -> true
isBadVersion(4) -> true
因此可以确定第四个版本是第一个错误版本。
Challenge
调用 isBadVersion 的次数越少越好
- Example
- n = :
- isBadVersion() -> false
- isBadVersion() -> true
- isBadVersion() -> true
- 因此可以确定第四个版本是第一个错误版本。
- Challenge
- 调用 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:
输入: [4, 5, 1, 2, 3] and target=1,
输出: 2.
例2:
输入: [4, 5, 1, 2, 3] and target=0,
输出: -1.
Challenge
O(logN) 时间限制
- class Solution:
- """
- @param A: an integer rotated sorted array
- @param target: an integer to be searched
- @return: an integer
- """
- def search(self, A, target):
- # write your code here
- length = len(A)
- if length>:
- left,right=,length-
- if A[]==target:
- return
- elif A[]>target:
- while left<=right:
- mid=(left+right)//
- if A[]<=A[mid]:
- left = mid+
- else:
- if A[mid]>target:
- right = mid-
- elif A[mid]<target:
- left = mid+
- else:
- return mid
- else:
- while left<=right:
- mid=(left+right)//
- if A[]>=A[mid]:
- right=mid-
- else:
- if A[mid]>target:
- right = mid-
- elif A[mid]<target:
- left = mid+
- else:
- return mid
- return -
- if __name__=="__main__":
- s = Solution()
- print(s.search([, , , , ],))
- print(s.search([, , , , ],))
- print(s.search([, ],))
62
(三). 双指针问题(Two Pointers)
228. Middle of Linked List
找链表的中点。
Example
样例 1:
输入: 1->2->3
输出: 2
样例解释: 返回中间节点的值
样例 2:
输入: 1->2
输出: 1
样例解释: 如果长度是偶数,则返回中间偏左的节点的值。
Challenge
如果链表是一个数据流,你可以不重新遍历链表的情况下得到中点么?
- #coding:utf-
- #Definition of ListNode
- class ListNode(object):
- def __init__(self, val, next=None):
- self.val = val
- self.next = next
- """
- @param head: the head of linked list.
- @return: a middle node of the linked list
- """
- class Solution:
- def middleNode(self, head):
- # write your code here
- slow = fast = head
- if head:
- while fast.next!=None and fast.next.next!=None:
- slow = slow.next
- fast = fast.next.next
- return slow
- if __name__=="__main__":
- s = Solution()
- list1 = ListNode(,ListNode(,ListNode()))
- list2 = ListNode(,ListNode())
- print(s.middleNode(list1).val)
- print(s.middleNode(list2).val)
228
607 Two Sum III -Data structure design
设计b并实现一个 TwoSum 类。他需要支持以下操作:add
和 find
。
add
-把这个数添加到内部的数据结构。
find
-是否存在任意一对数字之和等于这个值
Example
样例 1:
add(1);add(3);add(5);
find(4)//返回true
find(7)//返回false
- #coding:utf-
- #思路:遍历字典,求sum和遍历元素的差, 判断差是否也在字典中
- class TwoSum:
- """
- @param number: An integer
- @return: nothing
- """
- def __init__(self):
- self.numbers=dict()
- def add(self, number):
- # write your code here
- if number not in self.numbers:
- self.numbers[number]=
- else:
- self.numbers[number]+=
- """
- @param value: An integer
- @return: Find if there exists any pair of numbers which sum is equal to the value.
- """
- def find(self, value):
- # write your code here
- for key in self.numbers:
- target = value-key
- if target in self.numbers:
- if target!=key or self.numbers[target]>:
- return True
- return False
- #按顺序插入列表,find时前后指针遍历
- # class TwoSum:
- # """
- # @param number: An integer
- # @return: nothing
- # """
- # def __init__(self):
- # self.numbers=[]
- # def add(self, number):
- # # write your code here
- # length = len(self.numbers)
- # if length==:
- # self.numbers.append(number)
- # for i in range(length):
- # if self.numbers[i]>number:
- # self.numbers.insert(i,number)
- # break
- # if len(self.numbers)==length:
- # self.numbers.append(number)
- # """
- # @param value: An integer
- # @return: Find if there exists any pair of numbers which sum is equal to the value.
- # """
- # def find(self, value):
- # # write your code here
- # i,j=,len(self.numbers)-
- # while i<j:
- # if self.numbers[i]+self.numbers[j]==value:
- # return True
- # elif self.numbers[i]+self.numbers[j]>value:
- # j = j-
- # else:
- # i = i+
- # return False
- if __name__=="__main__":
- s = TwoSum()
- # s.add()
- # s.add()
- # s.add()
- # print(s.find())
- # print(s.find())
- # s.add()
- # s.add()
- # print(s.find())
- # print(s.find())
- # print(s.find())
- # s.add()
- # print(s.find())
- s.add()
- s.add()
- s.add()
- print(s.find())
- s.add()
- print(s.find())
- print(s.find())
- s.add()
- print(s.find())
- print(s.find())
607
539. Move Zeros
给一个数组 nums 写一个函数将 0
移动到数组的最后面,非零元素保持原数组的顺序
1.必须在原数组上操作
2.最小化操作数
Example
例1:
输入: nums = [0, 1, 0, 3, 12],
输出: [1, 3, 12, 0, 0].
例2:
输入: nums = [0, 0, 0, 3, 1],
输出: [3, 1, 0, 0, 0].
- #coding:utf-
- """
- 思路:
- 快慢指针:假设我们有一个新数组,有 根指针分别从老数组和新数组从前往后走,称老数组上的指针为「读指针」,新数组上的指针为「写指针」;只有当读指针所指向的数值非0时,才将读指针所指的数值写入到写指针所指的空间上,然后两根指针再继续向前走;当老数组遍历完时,只要将新数组继续填 直到新老数组长度一致即可。题目要求「就地操作」,那么实际上就不需要开这个新数组,只要让两根指针都在原数组上往前走就行:这是因为,读指针由于会跳过非 空间,其扫描速度远快于写指针,所有被读指针扫描过的非零值都会通过写指针写入「新的空间」中,因此所有被写指针覆盖掉的非零值,之前必定已经保存过了。该方法时间复杂度 O(n),空间复杂度 O()
- """
- """
- @param nums: an integer array
- @return: nothing
- """
- class Solution:
- def moveZeroes(self, nums):
- # write your code here
- i=j=
- while i<len(nums):
- if nums[i]!=:
- nums[j]=nums[i]
- j = j+
- i = i+
- while j<i:
- nums[j]=
- j = j+
- return nums
- if __name__=="__main__":
- s = Solution()
- print(s.moveZeroes([, , , , ]))
- print(s.moveZeroes([, , , , ]))
539
521 Remove Duplicate Numbers in Array
给一个整数数组,去除重复的元素。
你应该做这些事
1.在原数组上操作
2.将去除重复之后的元素放在数组的开头
3.返回去除重复元素之后的元素个数
Example
例1:
输入:
nums = [1,3,1,4,4,2]
输出:
(nums变为[1,3,4,2,?,?])
4
解释:
1. 将重复的整数移动到 nums 的尾部 => nums = [1,3,4,2,?,?].
2. 返回 nums 中唯一整数的数量 => 4.
事实上我们并不关心你把什么放在了 ? 处, 只关心没有重复整数的部分.
例2:
输入:
nums = [1,2,3]
输出:
(nums变为[1,2,3]
)3
- #coding:utf-
- """
- @param nums: an array of integers
- @return: the number of unique integers
- """
- #时间复杂度O(n),空间复杂度O(n)
- class Solution:
- def deduplication(self, nums):
- # write your code here
- nums_set=set()
- i=
- for num in nums:
- if num not in nums_set:
- nums_set.add(num)
- nums[i]=num
- i = i+
- return i
- #排序后使用双指针,时间复杂度O(nlogn),空间复杂度O()
- # class Solution:
- # def deduplication(self, nums):
- # # write your code here
- # length = len(nums)
- # if length<=:
- # return length
- # quicksort(nums,,length-)
- # i=j =
- # while i<length:
- # if nums[i]!=nums[i-]:
- # nums[j]=nums[i]
- # j = j+
- # i = i+
- # return j
- # def quicksort(nums,start,end):
- # if start<end:
- # pivot = start
- # left,right=start+,end
- # while left<=right:
- # while left<=right and nums[left]<=nums[pivot]:
- # left = left+
- # while left<=right and nums[right]>nums[pivot]:
- # right= right-
- # if left<=right:
- # nums[left],nums[right]=nums[right],nums[left]
- # nums[right],nums[pivot]=nums[pivot],nums[right]
- # quicksort(nums,start,right-)
- # quicksort(nums,right+,end)
- if __name__=="__main__":
- s = Solution()
- print(s.deduplication([,,,,,]))
- print(s.deduplication(nums = [,,]))
521
464 Sort Integers II
给一组整数,请将其在原地按照升序排序。使用归并排序,快速排序,堆排序或者任何其他 O(n log n) 的排序算法。
Description
给一组整数,请将其在原地按照升序排序。使用归并排序,快速排序,堆排序或者任何其他 O(n log n) 的排序算法。
Example
例1:
输入:[3,2,1,4,5],
输出:[1,2,3,4,5]。
例2:
输入:[2,3,1],
输出:[1,2,3]。
- """
- @param A: an integer array
- @return: nothing
- """
- class Solution:
- def sortIntegers2(self, A):
- # write your code here
- quicksort(A,,len(A)-)
- return A
- def quicksort(alist,start,end):
- if start<end:
- pivot=alist[start]
- left,right = start,end
- while left<right:
- while left<right and alist[right]>=pivot:
- right-=
- alist[left],alist[right]=alist[right],alist[left]
- while left<right and alist[left]<=pivot:
- left+=
- alist[right],alist[left]=alist[left],alist[right]
- quicksort(alist,start,left-)
- quicksort(alist,left+,end)
- if __name__=="__main__":
- s = Solution()
- print(s.sortIntegers2([, , , , ]))
- print(s.sortIntegers2([, , ]))
464
608. Two Sum II- Input array is sorted
给定一个已经 按升序排列 的数组,找到两个数使他们加起来的和等于特定数。
函数应该返回这两个数的下标,index1必须小于index2。注意返回的值不是 0-based
Example
例1:
输入: nums = [2, 7, 11, 15], target = 9
输出: [1, 2]
例2:
输入: nums = [2,3], target = 5
输出: [1, 2]
- class Solution:
- """
- @param nums: an array of Integer
- @param target: target = nums[index1] + nums[index2]
- @return: [index1 + , index2 + ] (index1 < index2)
- """
- def twoSum(self, nums, target):
- # write your code here
- length = len(nums)
- if length>:
- i,j=,length-
- while i<j:
- if nums[i]+nums[j]==target:
- return i+,j+
- elif nums[i]+nums[j]<target:
- i+=
- else:
- j-=
- if __name__=="__main__":
- s = Solution()
- print(s.twoSum(nums = [, , , ], target = ))
- print(s.twoSum(nums = [,], target = ))
608
143 Sort Colors II
给定一个有n个对象(包括k种不同的颜色,并按照1到k进行编号)的数组,将对象进行分类使相同颜色的对象相邻,并按照1,2,...k的顺序进行排序。
- 不能使用代码库中的排序函数来解决这个问题
k
<=n
Example
样例1
输入:
[3,2,2,1,4]
4
输出:
[1,2,2,3,4]
样例2
输入:
[2,1,1,2,2]
2
输出:
[1,1,2,2,2]
Challenge
一个相当直接的解决方案是使用计数排序扫描2遍的算法。这样你会花费O(k)的额外空间。你否能在不使用额外空间的情况下完成?
- #coding:utf-
- #思路参考:https://www.cnblogs.com/libaoquan/p/7226211.html (计数排序/桶排序改进)
- #输入[,,,,],进行一次遍历后变化过程如下:
- # [, , , , ]
- # [, , -, , ]
- # [, -, -, , ]
- # [, -, -, , ]
- # [-, -, -, , ]
- # [-, -, -, -, ]
- """
- @param colors: A list of integer
- @param k: An integer
- @return: nothing
- """
- class Solution:
- def sortColors2(self, colors, k):
- length = len(colors)
- if length<=:
- return colors
- #统计计数
- for i in range(length):
- while colors[i]>:
- index = colors[i]
- if colors[index-]>:
- colors[i]=colors[index-]
- colors[index-]=- #表示index出现一次
- elif colors[index-]<=:
- colors[i]=
- colors[index-]-= #表示index再次出现
- #输出排序结果
- j=length-
- for i in range(k-,-,-):
- temp = colors[i]
- while temp<:
- colors[j]=i+
- temp+=
- j-=
- return colors
- if __name__=="__main__":
- s = Solution()
- print(s.sortColors2([,,,,],))
- 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]]
- #coding:utf-
- """
- 题目: Three Sum
- Description:
- 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.
- 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 :
- Input:[,,,]
- Output:[]
- Example :
- Input:[-,,,,-,-]
- Output: [[-, , ],[-, -, ]]
- """
- """
- 思路:
- 由于设置了三个变量,故时间复杂度最少是O(n^)
- 在开头固定一个变量,然后一前一后 移动指针
- 和大于零 后指针前移
- 和小于零 前指针后移
- 和等于零 放入结果中,再让前后指针移动
- """
- """
- @param numbers: Give an array numbers of n integer
- @return: Find all unique triplets in the array which gives the sum of zero.
- """
- class Solution:
- def threeSum(self, numbers):
- # write your code here
- length = len(numbers)
- ret=[]
- if length<:
- return ret
- quicksort(numbers,,length-)
- print(numbers)
- for k in range(length-):
- if k== or numbers[k]!=numbers[k-]: #防止重复
- twoSum(numbers,-numbers[k],start=k+,end=length-,ret=ret)
- return ret
- def quicksort(numbers,start,end):
- if start<end:
- left,right=start,end
- pivot = numbers[start]
- while left<right:
- while left<right and numbers[right]>=pivot:
- right-=
- numbers[right],numbers[left]=numbers[left],numbers[right]
- while left<right and numbers[left]<pivot:
- left+=
- numbers[right],numbers[left]=numbers[left],numbers[right]
- quicksort(numbers,start,right-)
- quicksort(numbers,right+,end)
- def twoSum(numbers,target,start,end,ret):
- i,j = start,end
- while i<j:
- if numbers[i]+numbers[j]<target:
- i+=
- elif numbers[i]+numbers[j]>target:
- j-=
- else:
- if (-target)<numbers[i]:
- temp=[-target,numbers[i],numbers[j]]
- elif (-target)>numbers[j]:
- temp=[numbers[i],numbers[j],-target]
- else:
- temp=[numbers[i],-target,numbers[j]]
- if temp not in ret: #防止重复
- ret.append(temp)
- i+=
- j-=
- if __name__=="__main__":
- s = Solution()
- # print(s.threeSum([,,,]))
- # print(s.threeSum([-,,,,-,-]))
- # print(s.threeSum([,,-,-,-,-,,,,]))
- 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)?
- #coding:utf-
- """
- 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 :
- Input:
- [],
- Output:
- Example :
- Input:
- [,,,],
- Output:
- Explanation:
- the real array is[,,,].So return
- Challenge
- Can you partition the array in-place and in O(n)?
- """
- """
- 思路:类似于快速排序的左右指针
- """
- class Solution:
- """
- @param nums: The integer array you should partition
- @param k: An integer
- @return: The index after partition
- """
- def partitionArray(self, nums, k):
- # write your code here
- length=len(nums)
- if length==:
- return
- i,j=,length-
- while i<=j:
- while i<=j and nums[i]<k:
- i+=
- while i<=j and nums[j]>=k:
- j-=
- if i<j:
- nums[i],nums[j]=nums[j],nums[i]
- return i
- if __name__=="__main__":
- s = Solution()
- print(s.partitionArray([],))
- 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.
- #coding:utf-
- """
- 题目:. Kth Largest Element
- Description
- Find K-th largest element in an array.
- You can swap elements in the array
- Example :
- Input:
- n = , nums = [,,,]
- Output:
- Example :
- Input:
- n = , nums = [,,,,]
- Output:
- Challenge
- O(n) time, O() extra memory.
- """
- """
- 思路:
- 快速选择算法 的平均时间复杂度为 O(N){O}(N)O(N)。就像快速排序那样,本算法也是 Tony Hoare 发明的,因此也被称为 Hoare选择算法。
- 本方法大致上与快速排序相同。简便起见,注意到第 k 个最大元素也就是第 N - k 个最小元素,因此可以用第 k 小算法来解决本问题。
- 首先,我们选择一个枢轴,并在线性时间内定义其在排序数组中的位置。这可以通过 划分算法 的帮助来完成。
- 为了实现划分,沿着数组移动,将每个元素与枢轴进行比较,并将小于枢轴的所有元素移动到枢轴的左侧。
- 这样,在输出的数组中,枢轴达到其合适位置。所有小于枢轴的元素都在其左侧,所有大于或等于的元素都在其右侧。
- 这样,数组就被分成了两部分。如果是快速排序算法,会在这里递归地对两部分进行快速排序,时间复杂度为 O(NlogN)。
- 而在这里,由于知道要找的第 N - k 小的元素在哪部分中,我们不需要对两部分都做处理,这样就将平均时间复杂度下降到 O(N)。
- """
- class Solution:
- """
- @param n: An integer
- @param nums: An array
- @return: the Kth largest element
- """
- def kthLargestElement(self, n, nums):
- # write your code here
- length = len(nums)
- if n>length or n==:
- return None
- return half_quicksort(nums,n,,length-)
- #方法二,利用二叉堆
- def kthLargestElement2(self, n, nums):
- import heapq
- length = len(nums)
- if n>length or n==:
- return None
- return heapq.nlargest(n,nums)[n-]
- def half_quicksort(nums,k,start,end):
- if k== and start==end:
- return nums[start]
- if start<end:
- left,right=start,end
- pivot = nums[start]
- while left<right:
- while left<right and nums[right]>=pivot:
- right-=
- nums[left],nums[right]=nums[right],nums[left]
- while left<right and nums[left]<pivot:
- left+=
- nums[left],nums[right]=nums[right],nums[left]
- if end-right>k-:
- return half_quicksort(nums,k,right+,end)
- elif end-right<k-:
- return half_quicksort(nums,k-(end-right+),start,right-)
- else:
- return nums[right]
- if __name__=="__main__":
- s = Solution()
- print(s.kthLargestElement(n = , nums = [,,,]))
- print(s.kthLargestElement(n = , nums = [,,,,]))
- print(s.kthLargestElement2(n = , nums = [,,,]))
- 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
- #coding:utf-
- """
- . Number of Islands
- 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.
- Find the number of islands.
- Example
- Example :
- Input:
- [
- [,,,,],
- [,,,,],
- [,,,,],
- [,,,,],
- [,,,,]
- ]
- Output:
- Example :
- Input:
- [
- [,]
- ]
- Output:
- """
- """
- 思路:线性扫描整个二维网格,如果一个结点包含 ,则以其为根结点启动深度优先搜索。在深度优先搜索过程中,每个访问过的结点被标记为 。计数启动深度优先搜索的根结点的数量,即为岛屿的数量。
- """
- class Solution:
- """
- @param grid: a boolean 2D matrix
- @return: an integer
- """
- def numIslands(self, grid):
- # write your code here
- rows = len(grid)
- nums =
- if rows==:
- return nums
- for r in range(rows):
- cols = len(grid[r])
- if cols>:
- for c in range(cols):
- if grid[r][c]==:
- dfs(grid,r,c)
- nums+=
- return nums
- def dfs(grid,r,c):
- rows = len(grid)
- if r< or r>rows-:
- return
- cols = len(grid[r])
- if c< or c>cols-:
- return
- if grid[r][c]==:
- return
- grid[r][c]= #grid[r][c]=,将其由1设置为0,表示已经遍历
- dfs(grid,r-,c)
- dfs(grid,r+,c)
- dfs(grid,r,c-)
- dfs(grid,r,c+)
- if __name__=="__main__":
- s = Solution()
- g1 =[
- [,,,,],
- [,,,,],
- [,,,,],
- [,,,,],
- [,,,,]
- ]
- g2=[
- [,]
- ]
- print(s.numIslands(g1))
- 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.
- #coding:utf-
- """
- 题目:. 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 .
- Example :
- Input:{,,}
- Output:[[],[,]]
- Explanation:
- / \
- it will be serialized {,,}
- level order traversal
- Example :
- Input:{,#,,}
- Output:[[],[],[]]
- Explanation:
- \
- /
- it will be serialized {,#,,}
- level order traversal
- Challenge
- Challenge : Using only queue to implement it.
- Challenge : Use BFS algorithm to do it.
- """
- #Definition of TreeNode:
- class TreeNode:
- def __init__(self, val,left=None,right=None):
- self.val = val
- self.left, self.right = left, right
- class Solution:
- """
- @param root: A Tree
- @return: Level order a list of lists of integer
- """
- def levelOrder(self, root):
- # write your code here
- if not root:
- return []
- q=[[root]]
- ret=[]
- while q:
- val,temp=[],[]
- cur_list = q.pop()
- for cur in cur_list:
- if cur.left:
- temp.append(cur.left)
- if cur.right:
- temp.append(cur.right)
- if cur.val!="#":
- val.append(cur.val)
- if temp:
- q.append(temp)
- if val:
- ret.append(val)
- return ret
- if __name__=="__main__":
- s = Solution()
- #{,,}
- t1 = TreeNode(,TreeNode(),TreeNode())
- print(s.levelOrder(t1))
- #{,#,,}
- t2 = TreeNode(,TreeNode("#"),TreeNode(,TreeNode()))
- 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
- #coding:utf-
- """
- Description
- There are a total of n courses you have to take, labeled from to n - .
- Some courses may have prerequisites, for example to take course you have to first take course , which is expressed as a pair: [,]
- Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
- Example :
- Input: n = , prerequisites = [[,]]
- Output: true
- Example :
- Input: n = , prerequisites = [[,],[,]]
- Output: false
- """
- #思路:参考https://leetcode-cn.com/problems/course-schedule/solution/tuo-bu-pai-xu-by-liweiwei1419/
- """
- 拓扑排序
- 具体做如下:
- 、在开始排序前,扫描对应的存储空间(使用邻接表),将入度为 的结点放入队列。
- 、只要队列非空,就从队首取出入度为 的结点,将这个结点输出到结果集中,并且将这个结点的所有邻接结点(它指向的结点)的入度减 ,在减 以后,如果这个被减 的结点的入度为 ,就继续入队。
- 、当队列为空的时候,检查结果集中的顶点个数是否和课程数相等即可。
- """
- class Solution:
- """
- @param: numCourses: a total of n courses
- @param: prerequisites: a list of prerequisite pairs
- @return: true if can finish all courses or false
- """
- def canFinish(self, numCourses, prerequisites):
- # write your code here
- length = len(prerequisites)
- if length==:
- return True
- #初始化入度和邻接表(邻接表存放的是后继 successor 结点的集合)
- degree = [ for i in range(numCourses)]
- adj = [set() for i in range(numCourses)]
- # 想要学习课程 ,你需要先完成课程 ,我们用一个匹配来表示他们: [,]
- # [, ] 表示 在先, 在后,1的后继节点为0 (所以0这个节点的度加一)
- for second, first in prerequisites:
- if second not in adj[first]: #避免重复
- degree[second]+=
- adj[first].add(second)
- p=[]
- count =
- for i in range(len(degree)):
- if degree[i]==:
- p.append(i)
- while p:
- cur = p.pop()
- for j in adj[cur]:
- degree[j]-=
- if degree[j]==:
- p.append(j)
- count+=
- if count==numCourses:
- return True
- return False
- if __name__=="__main__":
- s = Solution()
- # print(s.canFinish(, prerequisites = [[,]] ))
- # print(s.canFinish(, prerequisites = [[,],[,]] ))
- 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]
- #coding:utf-
- """
- Description
- There are a total of n courses you have to take, labeled from to n - .
- Some courses may have prerequisites, for example to take course you have to first take course , which is expressed as a pair: [,]
- 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 :
- Input: n = , prerequisites = [[,]]
- Output: [,]
- Example :
- Input: n = , prerequisites = [[,],[,],[,],[,]]
- Output: [,,,] or [,,,]
- """
- class Solution:
- """
- @param: numCourses: a total of n courses
- @param: prerequisites: a list of prerequisite pairs
- @return: the course order
- """
- def findOrder(self, numCourses, prerequisites):
- # write your code here
- length = len(prerequisites)
- if length==:
- return [i for i in range(numCourses)]
- #初始化入度和邻接表(邻接表存放的是后继 successor 结点的集合)
- degree = [ for i in range(numCourses)]
- adj = [set() for i in range(numCourses)]
- # 想要学习课程 ,你需要先完成课程 ,我们用一个匹配来表示他们: [,]
- # [, ] 表示 在先, 在后,1的后继节点为0 (所以0这个节点的度加一)
- for second, first in prerequisites:
- if second not in adj[first]: #避免重复
- degree[second]+=
- adj[first].add(second)
- p=[]
- course = []
- for i in range(len(degree)):
- if degree[i]==:
- p.append(i)
- while p:
- cur = p.pop()
- for j in adj[cur]:
- degree[j]-=
- if degree[j]==:
- p.append(j)
- course.append(cur)
- if len(course)==numCourses:
- return course
- return []
- if __name__=="__main__":
- s = Solution()
- print(s.findOrder(, prerequisites = [[,]] ))
- 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
- #coding:utf-
- """
- 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 to n, with ≤ n ≤ ^.
- 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 :
- Input:org = [,,], seqs = [[,],[,]]
- Output: false
- Explanation:
- [,,] is not the only one sequence that can be reconstructed, because [,,] is also a valid sequence that can be reconstructed.
- Example :
- Input: org = [,,], seqs = [[,]]
- Output: false
- Explanation:
- The reconstructed sequence can only be [,].
- Example :
- Input: org = [,,], seqs = [[,],[,],[,]]
- Output: true
- Explanation:
- The sequences [,], [,], and [,] can uniquely reconstruct the original sequence [,,].
- Example :
- Input:org = [,,,,,], seqs = [[,,,],[,,,]]
- Output:true
- """
- # 拓扑排序:构建图和入度,按顺序遍历,验证唯一性
- # 拓扑排序的四种问法:
- # 求任意一个拓扑排序。
- # 问是否存在拓扑排序(course schedule )
- # 求所有拓扑排序(DFS)
- # 求是否存在且仅存在一个拓扑排序 (Queue中最多只有一个节点)
- class Solution:
- """
- @param org: a permutation of the integers from to n
- @param seqs: a list of sequences
- @return: true if it can be reconstructed only one or false
- """
- def sequenceReconstruction(self, org, seqs):
- # write your code here
- from collections import defaultdict
- # if len(seqs)== or len(org)==:
- # return False
- degree=dict()
- adj=defaultdict(set)
- for seq in seqs:
- for i in range(,len(seq)):
- if seq[i] not in degree:
- degree[seq[i]]=
- if i+<len(seq) and seq[i+] not in adj[seq[i]]:
- adj[seq[i]].add(seq[i+])
- if seq[i+] not in degree:
- degree[seq[i+]]=
- else:
- degree[seq[i+]]+=
- q=[i for i in degree.keys() if degree[i]==]
- ret=[]
- while q:
- cur = q.pop()
- for cur_adj in adj[cur]:
- degree[cur_adj]-=
- if degree[cur_adj]==:
- q.append(cur_adj)
- ret.append(cur)
- if ret==org: #可能有多个顺序,若相等则是唯一性
- return True
- return False
- if __name__=="__main__":
- s = Solution()
- print(s.sequenceReconstruction(org = [], seqs = [[]]))
- print(s.sequenceReconstruction(org = [,,], seqs = [[,],[,]]))
- print(s.sequenceReconstruction(org = [,,], seqs = [[,]]))
- print(s.sequenceReconstruction(org = [,,], seqs = [[,],[,],[,]]))
- 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
- #coding:utf
- """
- 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:
- {,,#,,#,#,,#,} represents follow graph:
- ------
- \ | |
- \ | |
- \ | |
- \ | |
- we use # to split each node information.
- ,, represents that , are 's neighbors
- ,, represents that , are 's neighbors
- , represents that is 's neighbor
- ,, represents that , are 's neighbors
- , represents that is 's neighbor
- Example1
- Input:
- {,,#,,#,,}
- Output:
- {,,#,,#,,}
- Explanation:
- ------
- \ |
- \ |
- \ |
- \ |
- """
- """
- Definition for a undirected graph node
- """
- class UndirectedGraphNode:
- def __init__(self, x):
- self.label = x
- self.neighbors = []
- """
- @param: node: A undirected graph node
- @return: A undirected graph node
- """
- class Solution:
- def cloneGraph(self, node):
- if node==None:
- return node
- root = node
- nodes=[]
- q={node}
- while q:
- cur = q.pop()
- nodes.append(cur)
- for i in cur.neighbors:
- if i not in nodes:
- q.add(i)
- # print(nodes)
- map=dict()
- for n in nodes:
- map[n]=UndirectedGraphNode(n.label)
- for n in nodes:
- temp = map[n]
- for ner in n.neighbors:
- temp.neighbors.append(map[ner])
- return map[root]
- if __name__=="__main__":
- node = UndirectedGraphNode()
- node.neighbors.append(UndirectedGraphNode())
- node.neighbors.append(UndirectedGraphNode())
- s = Solution()
- 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?
- #coding:utf
- """
- . 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:
- {,,#,,#,#,,#,} represents follow graph:
- ------
- \ | |
- \ | |
- \ | |
- \ | |
- we use # to split each node information.
- ,, represents that , are 's neighbors
- ,, represents that , are 's neighbors
- , represents that is 's neighbor
- ,, represents that , are 's neighbors
- , represents that is 's neighbor
- The topological order can be:
- [, , , , , ]
- [, , , , , ]
- ...
- Challenge
- Can you do it in both BFS and DFS?
- """
- """
- Definition for a Directed graph node
- class DirectedGraphNode:
- def __init__(self, x):
- self.label = x
- self.neighbors = []
- """
- class Solution:
- """
- @param: graph: A list of Directed graph node
- @return: Any topological order for the given graph.
- """
- def topSort(self, graph):
- # write your code here
- if len(graph)==:
- return graph
- degree=dict()
- seen=set()
- for node in graph:
- if node not in seen:
- seen.add(node)
- if node not in degree:
- degree[node]=
- for nb in node.neighbors:
- if nb not in degree:
- degree[nb]=
- else:
- degree[nb]+=
- order=[]
- while seen:
- node =seen.pop()
- if degree[node]==:
- order.append(node)
- for nb in node.neighbors:
- degree[nb]-=
- else:
- seen.add(node)
- 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.
- #coding:utf-
- """
- . 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 :
- Input:{,,,#,#,,}
- Output:{,,,#,#,,}
- Explanation:
- Binary tree {,,,#,#,,}, denote the following structure:
- / \
- / \
- it will be serialized {,,,#,#,,}
- Example :
- Input:{,,}
- Output:{,,}
- Explanation:
- Binary tree {,,}, denote the following structure:
- / \
- it will be serialized {,,}
- 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.
- """
- """
- Definition of TreeNode:
- class TreeNode:
- def __init__(self, val):
- self.val = val
- self.left, self.right = None, None
- """
- class Solution:
- """
- @param root: An object of TreeNode, denote the root of the binary tree.
- This method will be invoked first, you should design your own algorithm
- to serialize a binary tree which denote by a root node to a string which
- can be easily deserialized by your own "deserialize" method later.
- """
- def serialize(self, root):
- # write your code here
- if root==None:
- return root
- ret=[root.val]
- q=[root]
- while q:
- cur = q.pop()
- if cur.left!=None:
- q.append(cur.left)
- ret.append(cur.left.val)
- else:
- ret.append("#")
- if cur.right!=None:
- q.append(cur.right)
- ret.append(cur.right.val)
- else:
- ret.append("#")
- return ret
- """
- @param data: A string serialized by your serialize method.
- This method will be invoked second, the argument data is what exactly
- you serialized at method "serialize", that means the data is not given by
- system, it's given by your own serialize method. So the format of data is
- designed by yourself, and deserialize it here as you serialize it in
- "serialize" method.
- """
- def deserialize(self, data):
- # write your code here
- if data==None or len(data)==:
- return None
- root = TreeNode(data[])
- length=len(data)
- q=[root]
- i=
- while i<length and q:
- node = q.pop()
- if data[i]!="#":
- node.left = TreeNode(data[i])
- q.append(node.left)
- else:
- node.left=None
- if i+<length and data[i+]!="#" :
- node.right = TreeNode(data[i+])
- q.append(node.right)
- else:
- node.right=None
- i+=
- 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"
- #coding:utf-
- """
- . 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 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 :
- Input:start = "a",end = "c",dict =["a","b","c"]
- Output:
- Explanation:
- "a"->"c"
- Example :
- Input:start ="hit",end = "cog",dict =["hot","dot","dog","lot","log"]
- Output:
- Explanation:
- "hit"->"hot"->"dot"->"dog"->"cog"
- """
- #参考:https://leetcode-cn.com/problems/word-ladder/solution/dan-ci-jie-long-by-leetcode/
- class Solution:
- """
- @param: start: a string
- @param: end: a string
- @param: dict: a set of string
- @return: An integer
- """
- def ladderLength(self, start, end, dict):
- # write your code here
- if (not start) or (not end) or len(dict)==:
- return
- #构建图
- from collections import defaultdict
- graph = defaultdict(list)
- if start not in dict:
- dict.add(start)
- if end not in dict:
- dict.add(end)
- for word in dict:
- for i in range(len(word)):
- graph[word[:i]+"*"+word[i+:]].append(word)
- q=[(start,)]
- seen=set()
- #Breadth first search
- while q:
- cur,level = q.pop()
- for i in range(len(cur)):
- temp = cur[:i]+"*"+cur[i+:]
- for ner in graph[temp]:
- if ner==end:
- return level+
- if ner not in seen:
- q.append((ner,level+))
- seen.add(ner)
- # graph[temp]=[]
- return
- # class Solution:
- # """
- # @param: start: a string
- # @param: end: a string
- # @param: dict: a set of string
- # @return: An integer
- # """
- # def ladderLength(self, start, end, dict):
- # # write your code here
- # if (not start) or (not end) or len(dict)==:
- # return
- # #构建图
- # from collections import defaultdict
- # graph = defaultdict(list)
- # if start not in dict:
- # dict.append(start)
- # if end not in dict:
- # dict.append(end)
- # for i in dict:
- # for j in dict:
- # if i!=j and change_one(i,j):
- # graph[i].append(j)
- # q=[(start,)]
- # seen=set()
- # order=[]
- # #Breadth first search
- # while q:
- # cur,level = q.pop()
- # for word in graph[cur]:
- # if word==end:
- # return level+
- # if word not in seen:
- # q.append((word,level+))
- # seen.add(word)
- # return
- # def change_one(i,j):
- # length=len(i)
- # for n in range(length):
- # if i[:n]==j[:n] and i[n+:]==j[n+:]:
- # return True
- if __name__=="__main__":
- s = Solution()
- print(s.ladderLength(start = "a",end = "c",dict ={"a","b","c"}))
- 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
- #coding:utf-
- """
- . 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 = {,,,,#,,} and target = 6.124780
- Output:
- Explanation:
- Binary tree {,,,,#,,}, denote the following structure:
- / \
- / / \
- Example2
- Input: root = {,,,} and target = 4.142857
- Output:
- Explanation:
- Binary tree {,,,}, denote the following structure:
- / \
- /
- """
- """
- Definition of TreeNode:
- class TreeNode:
- def __init__(self, val):
- self.val = val
- self.left, self.right = None, None
- """
- """
- Definition of TreeNode:
- class TreeNode:
- def __init__(self, val):
- self.val = val
- self.left, self.right = None, None
- """
- class Solution:
- """
- @param root: the given BST
- @param target: the given target
- @return: the value in the BST that is closest to the target
- """
- def closestValue(self, root, target):
- # write your code here
- if root==None or target==None:
- return None
- ret,dif =root.val,abs(root.val-target)
- q=[root]
- while q:
- cur = q.pop()
- temp=abs(cur.val-target)
- if temp<dif:
- dif=temp
- ret = cur.val
- if cur.left !=None:
- q.append(cur.left)
- if cur.right !=None:
- q.append(cur.right)
- 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.
- #coding:utf-
- #https://www.lintcode.com/problem/minimum-subtree/description
- """
- . 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 :
- Input:
- {,-,,,,-,-}
- Output:
- Explanation:
- The tree is look like this:
- / \
- -
- / \ / \
- - -
- The sum of whole tree is minimum, so return the root.
- Example :
- Input:
- {}
- Output:
- Explanation:
- The tree is look like this:
- There is one and only one subtree in the tree. So we return .
- """
- #Definition of TreeNode:
- class TreeNode:
- def __init__(self, val):
- self.val = val
- self.left, self.right = None, None
- class Solution:
- """
- @param root: the root of binary tree
- @return: the root of the minimum subtree
- """
- import sys
- def __init__(self):
- self.ret=None
- self.minimum=sys.maxsize
- def findSubtree(self, root):
- # write your code here
- if root==None:
- return root
- self.cal_min_sum(root)
- # print(Solution.ret.val)
- return self.ret
- def cal_min_sum(self,node):
- if node==None:
- return
- temp = node.val+self.cal_min_sum(node.left)+self.cal_min_sum(node.right)
- if temp<self.minimum:
- self.minimum=temp
- self.ret=node
- return temp #必须得返回
- if __name__=="__main__":
- s = Solution()
- # root = TreeNode()
- # root.left,root.right=TreeNode(-),TreeNode()
- # root.left.left,root.left.right = TreeNode(),TreeNode()
- # root.right.left,root.right.right = TreeNode(-),TreeNode(-)
- root = TreeNode()
- root.right=TreeNode()
- 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
- #coding:utf-
- """
- Binary Tree Pathss
- Description
- Given a binary tree, return all root-to-leaf paths.
- Example :
- Input:{,,,#,}
- Output:["1->2->5","1->3"]
- Explanation:
- / \
- \
- Example :
- Input:{,}
- Output:["1->2"]
- Explanation:
- /
- """
- """
- Definition of TreeNode:
- class TreeNode:
- def __init__(self, val):
- self.val = val
- self.left, self.right = None, None
- """
- """
- Definition of TreeNode:
- class TreeNode:
- def __init__(self, val):
- self.val = val
- self.left, self.right = None, None
- """
- class Solution:
- """
- @param root: the root of the binary tree
- @return: all root-to-leaf paths
- """
- def binaryTreePaths(self, root):
- # write your code here
- if root==None:
- return []
- paths=[]
- self.helper(root,paths,"")
- return paths
- def helper(self,node,paths,tree):
- if node.left==None and node.right==None:
- paths.append(tree+str(node.val))
- if node.left!=None:
- self.helper(node.left,paths,tree+str(node.val)+"->")
- if node.right!=None:
- 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.
- #coding:utf-
- """
- . 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 :
- Input:{,,,,,#,}
- Output:{,#,,#,,#,,#,,#,}
- Explanation:
- / \
- / \ \
- \
- \
- \
- \
- \
- Example :
- Input:{}
- Output:{}
- Explanation:
- Challenge
- Do it in-place without any extra memory.
- """
- #参考:https://blog.csdn.net/c070363/article/details/51203408
- """
- Definition of TreeNode:
- class TreeNode:
- def __init__(self, val):
- self.val = val
- self.left, self.right = None, None
- """
- class Solution:
- """
- @param root: a TreeNode, the root of the binary tree
- @return: nothing
- """
- def flatten(self, root):
- # write your code here
- node = root
- while node:
- if node.left!=None:
- temp = node.left
- while temp.right:
- temp = temp.right
- temp.right = node.right
- node.right = node.left
- node.left=None
- node = node.right
- 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
- #coding:utf-
- """
- . 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 .
- Example :
- Input: tree = {,,}
- Output: true
- Explanation:
- This is a balanced binary tree.
- / \
- Example :
- Input: tree = {,,,#,#,,}
- Output: true
- Explanation:
- This is a balanced binary tree.
- / \
- / \
- Example :
- Input: tree = {,#,,,}
- Output: false
- Explanation:
- This is not a balanced tree.
- The height of node 's right sub-tree is 2 but left sub-tree is 0.
- \
- / \
- """
- #参考:https://www.jiuzhang.com/solutions/balanced-binary-tree/#tag-highlight-lang-python
- """
- Definition of TreeNode:
- class TreeNode:
- def __init__(self, val):
- self.val = val
- self.left, self.right = None, None
- """
- class Solution:
- """
- @param root: The root of binary tree.
- @return: True if this Binary tree is Balanced, or false.
- """
- def isBalanced(self, root):
- # write your code here
- balanced,_ = self.cal_balance(root)
- return balanced
- def cal_balance(self,node):
- if node==None:
- return True,
- balanced,leftHeight = self.cal_balance(node.left)
- if not balanced:
- return False,
- balanced,rightHeight = self.cal_balance(node.right)
- if not balanced:
- return False,
- dif = abs(leftHeight-rightHeight)
- 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?
- #coding:utf-
- """
- . 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, ≤ k ≤ BST's total elements.
- Example :
- Input:{,#,},
- Output:
- Explanation:
- \
- The second smallest element is .
- Example :
- Input:{,,},
- Output:
- Explanation:
- / \
- The first smallest element is .
- 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?
- """
- """
- Definition of TreeNode:
- class TreeNode:
- def __init__(self, val):
- self.val = val
- self.left, self.right = None, None
- """
- class Solution:
- """
- @param root: the given BST
- @param k: the given k
- @return: the kth smallest element in BST
- """
- def kthSmallest(self, root, k):
- # write your code here
- if root==None:
- return None
- vals=[]
- self.findElement(root,vals)
- return vals[k-]
- def findElement(self,node,vals):
- if node==None:
- return
- self.findElement(node.left,vals)
- vals.append(node.val)
- 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.
- #coding:utf-
- """
- . 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:
- {, , , #, #, , }
- Output:
- null
- Explanation:
- / \
- / \
- LCA(, ) =
- LCA(, ) =
- LCA(, ) =
- LCA(, ) = null
- Example2
- Input:
- {}
- Output:
- Explanation:
- The tree is just a node, whose value is .
- """
- """
- Definition of TreeNode:
- class TreeNode:
- def __init__(self, val):
- this.val = val
- this.left, this.right = None, None
- """
- class Solution:
- """
- @param: root: The root of the binary tree.
- @param: A: A TreeNode
- @param: B: A TreeNode
- @return: Return the LCA of the two nodes.
- """
- def lowestCommonAncestor3(self, root, A, B):
- # write your code here
- if root==None:
- return root
- foundA,foundB,ret=self.helper(root,A,B)
- if foundA and foundB:
- return ret
- def helper(self,node,A,B):
- if node==None:
- return False,False,None
- leftA,leftB,ret=self.helper(node.left,A,B)
- if leftA and leftB:
- return leftA,leftB,ret
- rightA,rightB,ret=self.helper(node.right,A,B)
- if rightA and rightB:
- return rightA,rightB,ret
- foundA = leftA or rightA
- foundB = leftB or rightB
- if foundA and foundB:
- return True,True,node
- if foundA==True:
- return True,node==B,node
- if foundB==True:
- return node==A,True,node
- 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.
- . 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 :
- Input: {-}
- Output:true
- Explanation:
- For the following binary tree(only one node):
- -
- This is a binary search tree.
- Example :
- Input: {,,,#,#,,}
- Output: true
- For the following binary tree:
- / \
- / \
- 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)?
- #coding:utf-
- """
- . 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 :
- Input:
- {}
- 0.000000
- Output:
- []
- Explanation:
- Binary tree {}, denote the following structure:
- Example :
- Input:
- {,,,#,}
- 0.275000
- Output:
- [,]
- Explanation:
- Binary tree {,,,#,}, denote the following structure:
- / \
- \
- Challenge
- Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?
- """
- #参考:https://www.jiuzhang.com/solution/closest-binary-search-tree-value-ii/#tag-highlight-lang-python
- #一次中序遍历得到排序链表,顺便记录一下最接近的数,接着用双指针从最接近的数向两边搜索,加入结果链表。
- """
- Definition of TreeNode:
- class TreeNode:
- def __init__(self, val):
- self.val = val
- self.left, self.right = None, None
- """
- class Solution:
- """
- @param root: the given BST
- @param target: the given target
- @param k: the given k
- @return: k values in the BST that are closest to the target
- """
- def closestKValues(self, root, target, k):
- # write your code here
- ret =[]
- if root==None:
- return ret
- import sys
- self.nearest = None
- self.dif=sys.maxsize
- self.helper(root,target,ret)
- i=j=ret.index(self.nearest)
- temp=[ret[i]]
- k-=
- while k> and i> and j<len(ret)-:
- if abs(ret[i-]-target)<=abs(ret[j+]-target):
- i-=
- temp.append(ret[i])
- else:
- j+=
- temp.append(ret[j])
- k-=
- if k>:
- if i==:
- temp.extend(ret[j+:j+k+])
- else:
- temp.extend(ret[i-k:i])
- return temp
- def helper(self,node,target,ret):
- if node==None:
- return
- if node.left:
- self.helper(node.left,target,ret)
- if abs(node.val-target)<self.dif:
- self.dif = abs(node.val-target)
- self.nearest=node.val
- ret.append(node.val)
- if node.right:
- 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)
- #coding:utf-
- """
- . 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() time in average.
- Example
- Input: {,,,#,,#,}
- Output: [, , , , ]
- Explanation:
- The BST is look like this:
- /\
- \ \
- You can return the inorder traversal of a BST [, , , , ]
- Example
- Input: {,,}
- Output: [,,]
- Explanation:
- The BST is look like this:
- / \
- You can return the inorder traversal of a BST tree [,,]
- Challenge
- Extra memory usage O(h), h is the height of the tree.
- Super Star: Extra memory usage O()
- """
- """
- Definition of TreeNode:
- class TreeNode:
- def __init__(self, val):
- self.val = val
- self.left, self.right = None, None
- Example of iterate a tree:
- iterator = BSTIterator(root)
- while iterator.hasNext():
- node = iterator.next()
- do something for node
- """
- class BSTIterator:
- """
- @param: root: The root of binary tree.
- """
- def __init__(self, root):
- # do intialization if necessary
- self.ret =[]
- self.traverse(root)
- self.length=len(self.ret)
- self.k=
- """
- @return: True if there has next node, or false
- """
- def hasNext(self, ):
- # write your code here
- if self.k<self.length:
- return True
- """
- @return: return next node
- """
- def next(self, ):
- # write your code here
- temp = self.ret[self.k]
- self.k+=
- return temp
- def traverse(self,root):
- if root==None:
- return
- if root.left:
- self.traverse(root.left)
- self.ret.append(root)
- if root.right:
- self.traverse(root.right)
86
详细代码可参见:https://github.com/silence-cho/cv-learning
lintcode刷题笔记(一)的更多相关文章
- LintCode刷题笔记-- LongestCommonSquence
标签:动态规划 题目描述: Given two strings, find the longest common subsequence (LCS). Your code should return ...
- LintCode刷题笔记-- PaintHouse 1&2
标签: 动态规划 题目描述: There are a row of n houses, each house can be painted with one of the k colors. The ...
- LintCode刷题笔记-- Maximum Product Subarray
标签: 动态规划 描述: Find the contiguous subarray within an array (containing at least one number) which has ...
- LintCode刷题笔记-- Maximal Square
标签:动态规划 题目描述: Given a 2D binary matrix filled with 0's and 1's, find the largest square containing a ...
- LintCode刷题笔记-- Edit distance
标签:动态规划 描述: Given two words word1 and word2, find the minimum number of steps required to convert wo ...
- LintCode刷题笔记-- Distinct Subsequences
标签:动态规划 题目描述: Given a string S and a string T, count the number of distinct subsequences of T in S. ...
- LintCode刷题笔记-- BackpackIV
标签: 动态规划 描述: Given an integer array nums with all positive numbers and no duplicates, find the numbe ...
- LintCode刷题笔记-- BackpackII
标记: 动态规划 问题描述: Given n items with size Ai, an integer m denotes the size of a backpack. How full you ...
- LintCode刷题笔记-- Update Bits
标签: 位运算 描述: Given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set ...
随机推荐
- LNMP环境搭建wordpress博客及伪静态
WordPress是使用PHP语言开发的博客平台,是一款开源的软件,用户可以在支持PHP和MySQL数据库的服务器上架设属于自己的网站.也可以把 WordPress当作一个内容管理系统(CMS)来使用 ...
- Django组件之用户认证
auth模块 1 from django.contrib import auth django.contrib.auth中提供了许多方法,这里主要介绍其中的三个: 1.1 .authenticate( ...
- 【OF框架】缓存Session/Cookies/Cache代码调用api,切换缓存到Redis
准备 缓存服务在应用开发中最常用的功能,特别是Session和Cookies,Cache部分业务开发过程会使用到. 在负载均衡环境下,缓存服务需要存储到服务器. 缓存默认实现在内存在,可以通过配置切换 ...
- Python 使用 docopt 解析json参数文件
1. 背景 在深度学习的任务中,通常需要比较复杂的参数以及输入输出配置,比如需要不同的训练data,不同的模型,写入不同的log文件,输出到不同的文件夹以免混淆输出 常用的parser.add()方法 ...
- Nutch2.1+mysql+solr3.6.1+中文网站抓取
1.mysql 数据库配置 linux mysql安装步骤省略. 在首先进入/etc/my.cnf (mysql为5.1的话就不用修改my.cnf,会导致mysql不能启动)在[mysqld] 下添加 ...
- 学到了林海峰,武沛齐讲的Day14完
全局变量和局部变量 局部里面定义 global name ======将局部变量变成全局变量 nonlocal name # nonlocal,指定上一级变量,如果没有就继续往上直到找到为止 有 ...
- 使用AJAX传输不了值时
当时候AJAX往后台传递值时 传不到后台 这时我们就要检查程序是否有问题了 一般AJAX程序 $.ajax( { type: "POST", url: "Login. ...
- Linux系统出现hung_task_timeout_secs和blocked for more than 120 seconds的解决方法
Linux系统出现系统没有响应. 在/var/log/message日志中出现大量的 “echo 0 > /proc/sys/kernel/hung_task_timeout_secs" ...
- bzoj 3629
给出数 $n$记 $f(x)$ 表示 $x$ 的因子和求出所有 $x$ 使得 $f(x) = n$考虑 $x = p_1 ^{a_1} * p_2 ^ {a_2} * \cdots * p_k ^ { ...
- 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 ...