python 常规算法100题

python 常规算法100题


2024年1月17日发(作者:)

python 常规算法

以下是一些常见的 Python 算法练习题(1-10题):

1. 两数之和:给定一个整数列表和一个目标值,在列表中找到两个数,使它们的和等于目标值,并返回这两个数的索引。

```python

def two_sum(nums, target):

hashmap = {}

for i, num in enumerate(nums):

complement = target - num

if complement in hashmap:

return [hashmap[complement], i]

hashmap[num] = i

```

2. 给定一个字符串,判断它是否是回文串。只考虑字母和数字字符,可以忽略大小写。

```python

def is_palindrome(s):

alphanumeric = [() for c in s if m()]

return alphanumeric == alphanumeric[::-1]

```

3. 旋转数组:给定一个数组,将数组中的元素向右移动 k 个位置,其中 k

是非负数。

```python

def rotate(nums, k):

k = k % len(nums)

nums[:] = nums[-k:] + nums[:-k]

```

4. 有效的括号:给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

```python

def is_valid(s):

stack = []

pairs = {')': '(', ']': '[', '}': '{'}

for char in s:

if char in pairs:

if not stack or () != pairs[char]:

return False

else:

(char)

return not stack

```

5. 合并两个有序链表:将两个升序链表合并为一个新的升序链表并返回。

```python

class ListNode:

def __init__(self, val=0, next=None):

= val

= next

def merge_two_lists(l1, l2):

dummy = ListNode()

curr = dummy

while l1 and l2:

if <= :

= l1

l1 =

else:

= l2

l2 =

curr =

= l1 if l1 else l2

return

```

6. 最长公共前缀:编写一个函数来查找字符串数组中的最长公共前缀字符串。如果不存在公共前缀,返回空字符串 ""。

```python

def longest_common_prefix(strs):

if not strs:

return ""

min_str = min(strs, key=len)

for i, char in enumerate(min_str):

for other in strs:

if other[i] != char:

return min_str[:i]

return min_str

```

7. 反转整数:给定一个 32 位有符号整数,将其反转并返回。若反转后整数溢出,则返回 0。

```python

def reverse(x):

sign = -1 if x < 0 else 1

x = abs(x)

res = 0

while x:

res = res * 10 + x % 10

x //= 10

res = sign * res

return res if -2**31 <= res <= 2**31 - 1 else 0

```

8. 字符串转换整数:实现一个函数,将字符串转换为整数。若字符串中存在多余的空格或非数字字符,则返回 0。若转换后的整数溢出,则返回 INT_MAX

(2^31 - 1) 或 INT_MIN (-2^31)。

```python

def my_atoi(s):

s = ()

if not s:

return 0

sign = -1 if s[0] == '-' else 1

if s[0] in ('-', '+'):

s = s[1:]

i = 0

res = 0

while i < len(s) and s[i].isdigit():

res = res * 10 + int(s[i])

i += 1

res = sign * res

res = max(min(res, 2**31 - 1), -2**31)

return res

```

9. 正则表达式匹配:给定一个字符串 s 和一个字符规律 p,请实现一个支持 '.' 和 '*' 的正则表达式匹配。

```python

def is_match(s, p):

if not p:

return not s

first_match = bool(s) and p[0] in {s[0], '.'}

if len(p) >= 2 and p[1] == '*':

return (is_match(s, p[2:]) or

first_match and is_match(s[1:], p))

return first_match and is_match(s[1:], p[1:])

```

10. 盛最多水的容器:给定一个非负整数数组,每个元素代表一个高度,找出两个高度之间的最大面积。

```python

def max_area(height):

max_area = 0

left = 0

right = len(height) - 1

while left < right:

area = min(height[left], height[right]) * (right - left)

max_area = max(max_area, area)

if height[left] < height[right]:

left += 1

else:

right -= 1

return max_area

```

这仅仅是一些常见的算法题目,可以通过练习更多的算法题目来提升自己的算法思维和编程能力。


发布者:admin,转转请注明出处:http://www.yc00.com/news/1705431217a1409023.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信