
目录
1. 最大数
给定一组非负整数 nums,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数。
注意:输出结果可能非常大,所以你需要返回一个字符串而不是整数。
示例 1:
输入:nums = [10,2] 输出:"210"
示例 2:
输入:nums = [3,30,34,5,9] 输出:"9534330"
示例 3:
输入:nums = [1] 输出:"1"
示例 4:
输入:nums = [10] 输出:"10"
提示:
1 <= nums.length <= 1000 <= nums[i] <= 10^9
代码:
class Solution(object):
def largestNumber(self, nums):
n = len(nums)
for i in range(n):
for j in range(n - i - 1):
temp_1 = str(nums[j])
temp_2 = str(nums[j + 1])
if int(temp_1 + temp_2) < int(temp_2 + temp_1):
temp = nums[j]
nums[j] = nums[j + 1]
nums[j + 1] = temp
output = ""
for num in nums:
output = output + str(num)
return str(int(output))
s = Solution()
nums = [10,2]
print(s.largestNumber(nums))
nums = [3,30,34,5,9]
print(s.largestNumber(nums))
输出:
210
9534330
2. 寻找峰值
峰值元素是指其值严格大于左右相邻值的元素。
给你一个整数数组 nums,找到峰值元素并返回其索引。数组可能包含多个峰值,在这种情况下,返回 任何一个峰值 所在位置即可。
你可以假设 nums[-1] = nums[n] = -∞ 。
你必须实现时间复杂度为 O(log n) 的算法来解决此问题。
示例 1:
输入:nums = [1,2,3,1] 输出:2 解释:3 是峰值元素,你的函数应该返回其索引 2。
示例 2:
输入:nums = [1,2,1,3,5,6,4] 输出:1 或 5 解释:你的函数可以返回索引 1,其峰值元素为 2; 或者返回索引 5, 其峰值元素为 6。
提示:
1 <= nums.length <= 1000-2^31 <= nums[i] <= 2^31 - 1- 对于所有有效的
i都有nums[i] != nums[i + 1]
代码:
class Solution:
def findPeakElement(self, nums: list) -> int:
low = 0
high = len(nums) - 1
while low < high:
mid = int(low - (low - high) / 2)
if nums[mid] < nums[mid + 1]:
low = mid + 1
else:
high = mid
return low
s = Solution()
nums = [1,2,3,1]
print(s.findPeakElement(nums))
nums = [1,2,1,3,5,6,4]
print(s.findPeakElement(nums))
输出:
2
5
3. 串联所有单词的子串
给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。
示例 1:
输入: s = "barfoothefoobarman", words = ["foo","bar"] 输出:[0,9] 解释:从索引 0 和 9 开始的子串分别是 "barfoo" 和 "foobar" 。输出的顺序不重要, [9,0] 也是有效答案。
示例 2:
输入: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"] 输出:[]
代码:
class Solution(object):
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
ls = len(s)
word_ls = len(words[0])
target_dict = {}
for word in words:
try:
target_dict[word] += 1
except KeyError:
target_dict[word] = 1
res = []
for start in range(ls - word_ls * len(words) + 1):
curr_dict = target_dict.copy()
for pos in range(start, start + word_ls * len(words), word_ls):
curr = s[pos:pos + word_ls]
try:
curr_dict[curr] -= 1
if curr_dict[curr] < 0:
break
except KeyError:
break
else:
res.append(start)
return res
if __name__ == '__main__':
sol = Solution()
s = "barfoothefoobarman"
words = ["foo","bar"]
print(sol.findSubstring(s, words))
s = "wordgoodgoodgoodbestword"
words = ["word","good","best","word"]
print(sol.findSubstring(s, words))
输出:
[0, 9]
[]
🌟 每日一练刷题专栏 🌟
✨ 持续,努力奋斗做强刷题搬运工!
👍 点赞,你的认可是我坚持的动力!
🌟 收藏,你的青睐是我努力的方向!
✎ 评论,你的意见是我进步的财富!
![]() | Golang每日一练 专栏 |
![]() | Python每日一练 专栏 |
![]() | C/C++每日一练 专栏 |
![]() | Java每日一练 专栏 |

文章提供了三道编程题目,包括排列数字以形成最大数、在数组中寻找峰值元素以及找字符串中由给定单词组成的子串。每题均给出了相应的解决方案,涉及字符串处理和数组操作,以及高效的搜索算法。




668

被折叠的 条评论
为什么被折叠?



