单调数列
如果数组是单调递增或单调递减的,那么它是 单调 的。
如果对于所有 i <= j,nums[i] <= nums[j],那么数组 nums 是单调递增的。 如果对于所有 i <= j,nums[i]> = nums[j],那么数组 nums 是单调递减的。
当给定的数组 nums 是单调数组时返回 true,否则返回 false。
代码:
#解法一
class Solution:
def isMonotonic(self, nums: List[int]) -> bool:
B = sorted(nums)
return B == nums or B == nums[::-1]
#解法二
class Solution:
def isMonotonic(self, nums: List[int]) -> bool:
a = 0
for i in range(len(nums)-1):
if nums[i] > nums[i+1]:
if a > 0:
return False
a = -1
elif nums[i] < nums[i+1]:
if a < 0:
return False
a = 1
else:
return True
内存和速度:
找出字符串中第一个匹配项的下标
题目:给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
#解法一:
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
a = len(needle)
for i in range(len(haystack)-a+1):
if haystack[i:i+a] == needle:
return i
else:
return -1
#解法二
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle not in haystack:
return -1
return haystack.find(needle)
内存和速度: