楼主: Myron2017
跳转到指定楼层
上一主题 下一主题
收起左侧

刷题记录帖子

🔗
 楼主| Myron2017 2026-4-3 11:27:09 | 只看该作者
全局:
157. Read N Characters Given Read4
Solved
Easy
Topics
conpanies icon
Companies
Given a file and assume that you can only read the file using a given method read4, implement a method to read n characters.

Method read4:

The API read4 reads four consecutive characters from file, then writes those characters into the buffer array buf4.

The return value is the number of actual characters read.

Note that read4() has its own file pointer, much like FILE *fp in C.

Definition of read4:

    Parameter:  char[] buf4
    Returns:    int

buf4[] is a destination, not a source. The results from read4 will be copied to buf4[].
Below is a high-level example of how read4 works:


File file("abcde"); // File is "abcde", initially file pointer (fp) points to 'a'
char[] buf4 = new char[4]; // Create buffer with enough space to store characters
read4(buf4); // read4 returns 4. Now buf4 = "abcd", fp points to 'e'
read4(buf4); // read4 returns 1. Now buf4 = "e", fp points to end of file
read4(buf4); // read4 returns 0. Now buf4 = "", fp points to end of file


Method read:

By using the read4 method, implement the method read that reads n characters from file and store it in the buffer array buf. Consider that you cannot manipulate file directly.

The return value is the number of actual characters read.

Definition of read:

    Parameters:        char[] buf, int n
    Returns:        int

buf[] is a destination, not a source. You will need to write the results to buf[].
Note:

Consider that you cannot manipulate the file directly. The file is only accessible for read4 but not for read.
The read function will only be called once for each test case.
You may assume the destination buffer array, buf, is guaranteed to have enough space for storing n characters.


Example 1:

Input: file = "abc", n = 4
Output: 3
Explanation: After calling your read method, buf should contain "abc". We read a total of 3 characters from the file, so return 3.
Note that "abc" is the file's content, not buf. buf is the destination buffer that you will have to write the results to.
Example 2:

Input: file = "abcde", n = 5
Output: 5
Explanation: After calling your read method, buf should contain "abcde". We read a total of 5 characters from the file, so return 5.
Example 3:

Input: file = "abcdABCD1234", n = 12
Output: 12
Explanation: After calling your read method, buf should contain "abcdABCD1234". We read a total of 12 characters from the file, so return 12.


Constraints:

1 <= file.length <= 500
file consist of English letters and digits.
1 <= n <= 1000
  1. """
  2. The read4 API is already defined for you.

  3.     @param buf4, a list of characters
  4.     [url=home.php?mod=space&uid=160137]@return[/url] an integer
  5.     def read4(buf4):

  6. # Below is an example of how the read4 API can be called.
  7. file = File("abcdefghijk") # File is "abcdefghijk", initially file pointer (fp) points to 'a'
  8. buf4 = [' '] * 4 # Create buffer with enough space to store characters
  9. read4(buf4) # read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e'
  10. read4(buf4) # read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i'
  11. read4(buf4) # read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file
  12. """

  13. class Solution:
  14.     def read(self, buf, n):
  15.         """
  16.         :type buf: Destination buffer (List[str])
  17.         :type n: Number of characters to read (int)
  18.         :rtype: The number of actual characters read (int)
  19.         """
  20.         
  21.         # 已读入到 buf 的字符总数
  22.         copied_chars = 0
  23.         # 临时缓冲区,用于存放 read4 读取的 4 个字符
  24.         buf4 = [''] * 4
  25.         
  26.         while copied_chars < n:
  27.             # 1. 从文件读取数据到临时缓冲区
  28.             count = read4(buf4)
  29.             
  30.             # 如果没读到数据,说明文件已经结束
  31.             if count == 0:
  32.                 break
  33.             
  34.             # 2. 计算本次实际需要拷贝多少个字符
  35.             # 剩余需要读取的字符数为 n - copied_chars
  36.             # 我们只能从 count 和 剩余需求量 之间取最小值
  37.             remaining_needed = n - copied_chars
  38.             curr_copy_count = min(count, remaining_needed)
  39.             
  40.             # 3. 将数据从临时缓冲区 buf4 拷贝到目标缓冲区 buf
  41.             for i in range(curr_copy_count):
  42.                 buf[copied_chars] = buf4[i]
  43.                 copied_chars += 1
  44.             
  45.             # 如果本次 read4 读到的字符少于 4 个,说明已经读到文件末尾了
  46.             if count < 4:
  47.                 break
  48.         
  49.         return copied_chars
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-4 09:01:57 | 只看该作者
全局:
LC 2075. Decode the Slanted Ciphertext
  1. class Solution:
  2.     def decodeCiphertext(self, encodedText: str, rows: int) -> str:
  3.         if not encodedText or rows == 0:
  4.             return ""
  5.         
  6.         n = len(encodedText)
  7.         ncols = int(n // rows)

  8.         ans = []

  9.         for i in range(ncols):
  10.             # process each slanted cols
  11.             r = 0
  12.             c = i
  13.             while r < rows and c < ncols:
  14.                 ans.append(encodedText[ r * ncols + c])
  15.                 r += 1
  16.                 c += 1
  17.         
  18.         return "".join(ans).rstrip()

  19.         
  20.         
复制代码
这道题目的核心是找到数组 index 和 decodedText 的对应规律,

r x cols + c


这里需要记住,decoded text 是按照 行存储的。

所以对于 (r,c) 在矩阵中的位置,需要跳过前面行的所有 cols,来排列在 加密text 里面。

实在不行,其实面试的时候,直接上例子吧,推算几个答案。
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-5 07:11:35 | 只看该作者
全局:
LC. 3707. Equal Score Substrings
  1. class Solution:
  2.     def scoreBalance(self, s: str) -> bool:
  3.         n = len(s)
  4.         pre_sum = [0] * (n+1)

  5.         for i in range(1, n+1):
  6.             pre_sum[i] = pre_sum[i-1] + (ord(s[i-1]) - ord('a') + 1)
  7.             
  8.         if pre_sum[n] % 2 == 1: return False
  9.         else:
  10.             for i in range(1, n):
  11.                 if pre_sum[i] == pre_sum[n] // 2:
  12.                     return True
  13.         
  14.         return False
  15.         
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-5 07:11:58 | 只看该作者
全局:
LC. 3701. Compute Alternating Sum
  1. class Solution:
  2.     def alternatingSum(self, nums: List[int]) -> int:
  3.         s = 0

  4.         for i in range(len(nums)):
  5.             if i % 2 == 1:
  6.                 s -= nums[i]
  7.             else:
  8.                 s += nums[i]
  9.         return s
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-5 11:01:36 | 只看该作者
全局:
LC. 3697. Compute Decimal Representation
  1. class Solution:
  2.     def decimalRepresentation(self, n: int) -> List[int]:
  3.         res = []
  4.         d = 0

  5.         while n:
  6.             c = n % 10
  7.             if c != 0: res.append(c * 10 ** d)
  8.             d += 1
  9.             n = n // 10

  10.         

  11.         return res[::-1]
  12.         
复制代码
优化,用数字 p 来记录当前的位数,而不是用幂来记录。

不过也不是啥大优化。
  1. class Solution:
  2.     def decimalRepresentation(self, n: int) -> list[int]:
  3.         res = []
  4.         # 我们从低位向高位处理,但为了降序,我们可以先拿到所有结果再翻转
  5.         # 或者直接计算当前 n 的最大量级。为了简洁,翻转你的思路是最稳的。
  6.         p = 1
  7.         while n > 0:
  8.             digit = n % 10
  9.             if digit != 0:
  10.                 res.append(digit * p)
  11.             n //= 10
  12.             p *= 10
  13.         
  14.         return res[::-1] # 降序排列
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-5 11:11:00 | 只看该作者
全局:
LC. 657. Robot Return to Origin
  1. class Solution:
  2.     def judgeCircle(self, moves: str) -> bool:
  3.         directions = { 'R': (1, 0), 'L': (-1, 0), 'U': (0, 1), 'D': (0, -1)}
  4.         x, y = 0, 0
  5.         
  6.         for move in moves:
  7.             x += directions[move][0]
  8.             y += directions[move][1]

  9.         return x == 0 and y == 0
  10.             
  11.         
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-6 03:29:42 | 只看该作者
全局:
LC 3692. Majority Frequency Characters
  1. class Solution:
  2.     def majorityFrequencyGroup(self, s: str) -> str:
  3.         count = Counter(s)

  4.         freq_group = defaultdict(list)

  5.         for key, val in count.items():
  6.             freq_group[val].append(key)

  7.         freq_list = []

  8.         for key, val in freq_group.items():
  9.             freq_list.append((len(val), key))
  10.         freq_list.sort(reverse = True)

  11.         return "".join(freq_group[freq_list[0][1]])
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-6 03:32:19 | 只看该作者
全局:
LC. 3696. Maximum Distance Between Unequal Words in Array I
Solved
Easy
Topics
Hint
You are given a string array words.

Find the maximum distance between two distinct indices i and j such that:

words[i] != words[j], and
the distance is defined as j - i + 1.
Return the maximum distance among all such pairs. If no valid pair exists, return 0.



Example 1:

Input: words = ["leetcode","leetcode","codeforces"]

Output: 3

Explanation:

In this example, words[0] and words[2] are not equal, and they have the maximum distance 2 - 0 + 1 = 3.

Example 2:

Input: words = ["a","b","c","a","a"]

Output: 4

Explanation:

In this example words[1] and words[4] have the largest distance of 4 - 1 + 1 = 4.

Example 3:

Input: words = ["z","z","z"]

Output: 0

Explanation:

In this example all the words are equal, thus the answer is 0.



Constraints:

1 <= words.length <= 100
1 <= words[i].length <= 10
words[i] consists of lowercase English letters.


我的解法,其实还是记录第一次出现的单词的位置,
  1. class Solution:
  2.     def maxDistance(self, words: List[str]) -> int:
  3.         w_ind = dict()
  4.         max_dist = float('-inf')

  5.         for ind, w in enumerate(words):

  6.             for w_pre in w_ind:
  7.                 if w_pre != w:
  8.                     max_dist = max(max_dist, ind - w_ind[w_pre]+1)
  9.             
  10.             if w not in w_ind:
  11.                 w_ind[w] = ind
  12.         if max_dist == float('-inf'):
  13.             return 0
  14.         else:
  15.             return max_dist

  16.         
复制代码
但是可以简化逻辑,

我们只需要锁定两个特殊的“最左侧”位置:

first_idx: 整个数组第一个词的下标(即 0)。

diff_idx: 整个数组中,第一个与第一个词不同的词的下标。
其实我们不需要遍历字典里的每一个单词。要让距离最大,只需要考虑两种情况:

当前词 words[j] 和全数组最左边的词 words[0] 比较(如果它们不等)。

如果 words[j] 恰好等于 words[0],那它只能和全数组第一个与 words[0] 不相等的词比较。
  1. class Solution:
  2.     def maxDistance(self, words: List[str]) -> int:
  3.         n = len(words)
  4.         # 找到第一个和 words[0] 不一样的词的位置
  5.         diff_idx = -1
  6.         for i in range(1, n):
  7.             if words[i] != words[0]:
  8.                 diff_idx = i
  9.                 break
  10.         
  11.         # 如果没找到,说明全数组都一样
  12.         if diff_idx == -1:
  13.             return 0
  14.             
  15.         max_dist = 0
  16.         for j in range(n):
  17.             # 情况 1:当前词不等于第一个词,跟第一个词比
  18.             if words[j] != words[0]:
  19.                 max_dist = max(max_dist, j - 0 + 1)
  20.             # 情况 2:当前词等于第一个词,跟第一个不同的词(diff_idx)比
  21.             else:
  22.                 max_dist = max(max_dist, j - diff_idx + 1)
  23.                
  24.         return max_dist
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-7 10:35:30 | 只看该作者
全局:
LC 874. Walking Robot Simulation
  1. class Solution:
  2.     def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:
  3.         direction = (0, 1)
  4.         x = 0
  5.         y = 0
  6.         ans = -1

  7.         obstacles = set((o[0], o[1]) for o in obstacles )

  8.         for command in commands:
  9.             if command == -2:
  10.                 d1, d2 = direction
  11.                 direction = (-1 * d2, d1)
  12.             elif command == -1:
  13.                 d1, d2 = direction
  14.                 direction  = (d2 , -1 * d1)
  15.             else:
  16.                 for i in range(command):
  17.                     tmp_x, tmp_y = x + direction[0], y + direction[1]
  18.                     if (tmp_x, tmp_y) in obstacles:
  19.                         break
  20.                     else:
  21.                         ans = max(ans, tmp_x **2 + tmp_y **2)
  22.                         x, y = tmp_x, tmp_y
  23.         
  24.         return max(ans, 0)
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-4-8 10:30:24 | 只看该作者
全局:
LC. 3653. XOR After Range Multiplication Queries I

数据量小,直接暴力解决。

当然我犯了个错,用了 OR 而不是 XOR; 也忘记了 XOR 的性质。
  1. # 你的代码:
  2. for i in range(1, len(nums)):
  3.     ans = ans | nums[i]  # ❌ 这里的 '|' 是按位或 (OR)

  4. # 正确写法:
  5. for i in range(1, len(nums)):
  6.     ans = ans ^ nums[i]  # ✅ 这里的 '^' 是按位异或 (XOR)
复制代码
异或的初始值技巧:根据异或的性质 0 ^ X = X,我们可以直接把初始值设为 0,然后遍历整个数组,这样就不需要把 nums[0] 单独拎出来,代码更整洁。
  1. class Solution:
  2.     def xorAfterQueries(self, nums: List[int], queries: List[List[int]]) -> int:
  3.         mod = 10**9 + 7
  4.         for q in queries:
  5.             l, r, k, v = q
  6.             for i in range(l, r+1, k):
  7.                 nums[i] = (nums[i] * v) % mod
  8.         
  9.         ans = 0

  10.         for num in nums:
  11.             ans = ans ^ num

  12.         return ans  
复制代码
当然这题,如果数据量扩大,就是 Hard 了,3655. XOR After Range Multiplication Queries II
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表