• 题目要求

image.png

  • 思路:

    • 定义一个数组mylist,长度与给定的数组长度相同
    • 对数组进行迭代,依次把数组的值插入mylist中,用maxlen表示当前已经插入数组元素的长度

      • 如果当前的元素在已经插入的元素的某两个值之间,把这个值赋给两个值中较大的(如果当前插入元素为4,已经插入的序列是1,3,6,7,可知4大于3,小于6,如果后续还有5,那么依旧可以与1,3,4,7组成新的递增序列,而6不行)
      • 如果当前的元素比mylist中的所有元素都大,把他加在mylist[已经插入的数组长度]的位置(因为长度比下标多1)
  • 核心代码:
# 定义已经插入的序列的长度
maxlen = 0
# 定义新的列表
mylist = [0] * len(nums)

# 遍历题中的列表
for j in nums:
    # 此处用二分查找,因为是排好序的序列,所以每次只与中间值比较
    low , high = 0 , maxlen
    while low < high:
        mid = low + (high - low) // 2
        if mylist[mid] < j:
            low = mid + 1
        else:
            high = mid
   
    mylist[low] = j
    if low == maxlen:
        maxlen += 1
    print mylist

return maxlen
  • 完整代码:
class Solution(object):
    def lengthOfLIS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        maxlen = 0
        mylist = [0] * len(nums)

        for j in nums:
            low , high = 0 , maxlen
            while low < high:
                mid = low + (high - low) // 2
                if mylist[mid] < j:
                    low = mid + 1
                else:
                    high = mid

            mylist[low] = j
            if low == maxlen:
                maxlen += 1
            print mylist

        return maxlen


Adrianna
1 声望2 粉丝