给定一个整数数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。
你找到的子数组应是最短的,请输出它的长度。
示例 1:
输入: [2, 6, 4, 8, 10, 9, 15]
输出: 5
解释: 你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。
说明 :
输入的数组长度范围在 [1, 10,000]。
输入的数组可能包含重复元素 ,所以升序的意思是<=。
##py,使用双指针,然后对比,一个指前面,一个指后面
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
sorted_nums = sorted(nums)
p1 = 0
p2 = len(nums)-1
while p1 <= p2 and sorted_nums[p1] == nums[p1]:
p1 += 1
while p1 <= p2 and sorted_nums[p2] == nums[p2]:
p2 -= 1
return p2-p1+1
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: “()”
输出: true
示例 2:
输入: “()[]{}”
输出: true
示例 3:
输入: “(]”
输出: false
示例 4:
输入: “([)]”
输出: false
示例 5:
输入: “{[]}”
输出: true
##这个思路就nm离谱,replace函数牛逼
class Solution:
def isValid(self, s: str) -> bool:
while '()' in s or '{}' in s or '[]' in s:
s = s.replace('()','')
s = s.replace('{}','')
s = s.replace('[]','')
return s==''
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
##数学真尼玛神奇,裂开
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
s1 = 0
s2 = 0
t = 1
while head!=None:
s1 = s1*10 + head.val
s2 = s2 + t*head.val
t *= 10
head = head.next
return s1 == s2