python刷题③

11、container with most water

题目描述:

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

Notice that you may not slant the container.

def maxArea(height):
    max_water = 0
    left, right = 0, len(height) - 1

    while left < right:
        h_left, h_right = height[left], height[right]
        width = right - left
        min_height = min(h_left, h_right)
        area = width * min_height
        max_water = max(max_water, area)

        # Move the pointer associated with the shorter line
        if h_left < h_right:
            left += 1
        else:
            right -= 1

    return max_water

# Example usage
height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
print(maxArea(height))  # Output: 49

在这段代码中,我们初始化分别指向数组开头和结尾的左指针和右指针。我们使用较短的线计算面积,如果当前面积较大,则更新max_water。然后,我们将与较短线相关联的指针移向另一个指针。这个过程一直持续到指针相遇,保证我们已经探索了所有可能的容器。
该算法的时间复杂度为O(n),其中n是输入数组高度的长度,因为我们只需要通过数组一次。

12、integer to roman

题目描述:

Roman numerals are represented by seven different symbols: IVXLCD and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given an integer, convert it to a roman numeral.

def intToRoman(num):
    val_to_symbol = {
        1000: 'M',
        900: 'CM',
        500: 'D',
        400: 'CD',
        100: 'C',
        90: 'XC',
        50: 'L',
        40: 'XL',
        10: 'X',
        9: 'IX',
        5: 'V',
        4: 'IV',
        1: 'I'
    }

    roman = ""
    for value, symbol in sorted(val_to_symbol.items(), reverse=True):
        while num >= value:
            roman += symbol
            num -= value

    return roman

# Example usage
num = 1994
print(intToRoman(num))  # Output: "MCMXCIV"

在这段代码中,我们从可能的最大值(例如,1000900500等)开始,并不断从num中减去它们,同时将相应的符号添加到罗马字符串中。我们使用字典val_to_symbol来定义值和符号之间的映射,并按降序遍历该字典以处理减法的情况(例如,4、9、40、90等)。
该算法的时间复杂度为O(13),因为val_to_symbol字典中有13个唯一值,因此将整数转换为罗马数字非常有效。

13、roman to integer

题目描述:

Roman numerals are represented by seven different symbols: IVXLCD and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer.

def romanToInt(s):
    roman_to_int = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    }

    result = 0
    prev = 0

    for char in s:
        curr = roman_to_int[char]
        if curr > prev:
            result += curr - 2 * prev
        else:
            result += curr
        prev = curr

    return result

# 示例输入
roman = "MCMXCIV"

# 调用函数并打印结果
print(romanToInt(roman))  # 输出 1994

这个算法首先初始化映射字典,然后遍历罗马数字字符串,根据当前字符对应的整数值和前一个字符对应的整数值来计算最终的整数表示。这个算法的时间复杂度为O(n),其中n是输入字符串 s 的长度。

14、longest common prefix

题目描述:

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

def longestCommonPrefix(strs):
    if not strs:
        return ""

    prefix = strs[0]
    for string in strs:
        while string.find(prefix) != 0:
            prefix = prefix[:-1]
            if not prefix:
                return ""

    return prefix

# 示例输入
strs = ["flower", "flow", "flight"]

# 调用函数并打印结果
print(longestCommonPrefix(strs))  # 输出 "fl"

这个算法首先将第一个字符串作为当前的公共前缀 prefix,然后遍历数组中的每个字符串,通过不断缩短 prefix 直到它成为当前字符串的公共前缀。如果在这个过程中 prefix 变为空字符串,就返回空字符串,否则返回 prefix 作为最终的最长公共前缀。这个算法的时间复杂度为 O(n*m),其中 n 是数组中字符串的数量,m 是最长公共前缀的长度。

15、3sum

题目描述:

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != ji != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

def threeSum(nums):
    nums.sort()  # Sort the array in ascending order
    triplets = []

    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue  # Skip duplicates for the first element of the triplet

        left, right = i + 1, len(nums) - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total == 0:
                triplets.append([nums[i], nums[left], nums[right]])
                left += 1
                right -= 1

                # Skip duplicates for the second and third elements of the triplet
                while left < right and nums[left] == nums[left - 1]:
                    left += 1
                while left < right and nums[right] == nums[right + 1]:
                    right -= 1
            elif total < 0:
                left += 1
            else:
                right -= 1

    return triplets

# Example usage
nums = [-1, 0, 1, 2, -1, -4]
print(threeSum(nums))  # Output: [[-1, -1, 2], [-1, 0, 1]]

在此代码中:
我们按升序对输入数组nums进行排序。
我们遍历已排序的数组,并使用两个指针(左和右)来找到和为零的三元组。
我们跳过三元组的第一个元素(nums[i])以及三元组的第二个和第三个元素(nums[left]和nums[right])的重复,以避免结果中出现重复的三元组。
该算法确保解集不包含重复的三元组,并且时间复杂度为O(n^2),其中n是输入数组nums的长度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值