1.搜索旋转排序数组
class Solution ( object ) :
def search ( self, nums, target) :
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
minIndex = self. finMin( nums)
if target > nums[ - 1 ] :
left, right = 0 , minIndex - 1
else :
left, right = minIndex, len ( nums) - 1
while left <= right:
mid = left + ( right - left) / 2
if nums[ mid] > target:
right = mid - 1
elif nums[ mid] < target:
left = mid + 1
else :
return mid
return - 1
def finMin ( self, nums) :
left, right = 0 , len ( nums) - 1
if len ( nums) == 1 or nums[ left] < nums[ right] :
return left
while left <= right:
mid = ( left + right) / 2
if nums[ mid] >= nums[ 0 ] :
left = mid + 1
elif nums[ mid] > nums[ mid - 1 ] :
right = mid - 1
else :
return mid
return left
2.寻找两个正序数组的中位数
class Solution ( object ) :
def findMedianSortedArrays ( self, nums1, nums2) :
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
nums = nums1 + nums2
n = len ( nums)
nums = sorted ( nums)
if n <= 1 :
return nums[ 0 ]
left = 0
if n % 2 == 0 :
while left <= n/ 2 :
left += 1
return ( nums[ left - 2 ] + nums[ left - 1 ] ) / 2.0
else :
while left < n/ 2 :
left += 1
return nums[ left]
3.有效的括号
class Solution ( object ) :
def isValid ( self, s) :
"""
:type s: str
:rtype: bool
"""
stack = [ ]
if len ( s) % 2 != 0 :
return False
for ch in s:
if ch == "(" :
stack. append( ")" )
elif ch == "{" :
stack. append( "}" )
elif ch == "[" :
stack. append( "]" )
elif ch in [ "}" , "]" , ")" ] :
if not stack:
return False
elif stack. pop( ) != ch:
return False
if not stack:
return True
else :
return False
4.最小栈
class MinStack ( object ) :
def __init__ ( self) :
self. stack = [ ]
def push ( self, val) :
"""
:type val: int
:rtype: None
"""
if not self. stack:
self. stack. append( ( val, val) )
else :
self. stack. append( ( val, min ( self. stack[ - 1 ] [ 1 ] , val) ) )
def pop ( self) :
"""
:rtype: None
"""
self. stack. pop( )
def top ( self) :
"""
:rtype: int
"""
return self. stack[ - 1 ] [ 0 ]
def getMin ( self) :
"""
:rtype: int
"""
return self. stack[ - 1 ] [ 1 ]
5.字符串解码
class Solution ( object ) :
def decodeString ( self, s) :
"""
:type s: str
:rtype: str
"""
stack, res, multi = [ ] , "" , 0
for c in s:
if "0" <= c <= "9" :
multi = multi * 10 + int ( c)
elif c == "[" :
stack. append( [ multi, res] )
res, multi = "" , 0
elif c == "]" :
cur_multi, cur_res = stack. pop( )
res = cur_res + cur_multi * res
else :
res += c
return res