📅  最后修改于: 2023-12-03 15:00:25.034000             🧑  作者: Mango
本篇介绍了来自Directi面试中的一组编程问题,这组问题共计7个,涵盖了不同难度级别的编程题目。这些问题旨在帮助程序员提高算法和数据结构的能力。
下面是一组编程问题,包括了每个问题的简要描述和要求。具体的解决方案和代码片段将在后面给出。
问题1: 数组中的两个元素之和
问题2: 判断是否是回文数
问题3: 不同路径
问题4: 链表倒数第k个节点
问题5: 求解平方根
问题6: 寻找缺失的数
问题7: 奇偶链表
下面给出了每个问题的示例代码片段,这些代码片段使用Markdown格式进行标记。
```python
def find_sum_indices(nums, target):
num_to_index = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_to_index:
return [num_to_index[complement], i]
num_to_index[num] = i
2. **问题2: 判断是否是回文数**
```markdown
```python
def is_palindrome(num):
if num < 0:
return False
reversed_num, original_num = 0, num
while num > 0:
reversed_num = reversed_num * 10 + num % 10
num //= 10
return reversed_num == original_num
3. **问题3: 不同路径**
```markdown
```python
def unique_paths(grid):
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
dp = [[0] * n for _ in range(m)]
dp[0][0] = 1 if grid[0][0] == 0 else 0
for i in range(1, m):
dp[i][0] = dp[i-1][0] if grid[i][0] == 0 else 0
for j in range(1, n):
dp[0][j] = dp[0][j-1] if grid[0][j] == 0 else 0
for i in range(1, m):
for j in range(1, n):
if grid[i][j] == 0:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[-1][-1]
4. **问题4: 链表倒数第k个节点**
```markdown
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def get_kth_from_end(head, k):
fast = slow = head
for _ in range(k):
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
return slow.val
5. **问题5: 求解平方根**
```markdown
```python
def sqrt(x):
if x < 2:
return x
left, right = 0, x
while left < right:
mid = (left + right) // 2
if mid * mid <= x < (mid + 1) * (mid + 1):
return mid
elif mid * mid > x:
right = mid
else:
left = mid + 1
6. **问题6: 寻找缺失的数**
```markdown
```python
def find_missing_number(nums):
n = len(nums)
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum
7. **问题7: 奇偶链表**
```markdown
```python
def odd_even_list(head):
if not head:
return head
odd = head
even = even_head = head.next
while even and even.next:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
odd.next = even_head
return head
以上是这组编程问题的解决方案和示例代码,希望能对程序员们进行算法和数据结构的训练有所帮助。