某公司笔试编程题

  1. 前k个最小数
#python版本
class Solution:
    def GetLeastNumbers_Solution(self, input, k):
        n = len(input)
        if k<=0 or k>n:
            return
        #对input中前k个数建立大根堆, input从0开始,即input[0:k-1] 为一个大根堆
        for i in range(int(k/2), -1, -1):
            self.adjustHeap(input, i, k-1)
        for i in range(k, n):
            if input[i] < input[0]:
                input[0], input[i] = input[i], input[0]
                #调整前k个数
                self.adjustHeap(input, 0, k-1)
        print(input[:k])

    def adjust(self, nums, start, end):
        temp = nums[start]
        child = 2*start+1

        while child <= end:
            if child+1 <=end and nums[child] < nums[child+1]:
                #如果右孩子比较大,下标向右移
                child += 1
            if temp >= nums[child]:
                break
            #如果根小于某个孩子, 将较大值提到跟位置
            nums[start] = nums[child]

            start = child
            #孩子下标降一层
            child = start*2+1
        nums[start] = temp
  1. 有效字符串括号长度
#python版本
def longest_valid_parentheses(s):   #利用动态规划的思想
    maxlen = 0
    dp = [0 for i in range(len(s))]
    for i in range(1, len(s)):
        if s[i] == ')':
            if s[i-1] == '(':
                dp[i] = dp[i-2] +2 if i>2 else 2
            elif i-dp[i-1]>0 and s[i-dp[i-1]-1] == '(':
                tmp = dp[i-dp[i-1]-2] if i-dp[i-1]>=2 else 0
                dp[i] = dp[i-1]+2+tmp
            maxlen = max(maxlen, dp[i])
    return maxlen

你可能感兴趣的:(力扣算法C++版本)