- 盛最多水的容器
给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器
思路:设置左右两个指针left 和 right,盛水容量由矮的高度决定,每次移动矮的高度
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
l = 0
r = len(height)-1
if not height or len(height) == 1 :
return 0
res = (r-l)*(height[l] if height[l] < height[r] else height[r])
while l < r:
if height[l] < height[r] :
res = res if res > height[l]*(r-l) else height[l]*(r-l)
l += 1
else :
res = res if res > height[r]*(r-l) else height[r]*(r-l)
r -=1
return res
- 最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入:strs = [“flower”,“flow”,“flight”]
输出:“fl”
示例 2:
输入:strs = [“dog”,“racecar”,“car”]
输出:""
解释:输入不存在公共前缀。
暴力方法好像会超时,但是看到下面这个暴力循环方法,不超时。
循环对比第一个字母,初始t为"",若首位全相同则追加至t并对比下一位,不相同则返回t
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs)==0:
return ""
t=""
flag=0
strs=sorted(strs,key=lambda x:len(x))
for n in range(len(strs[0])):
temp=strs[0][n]
for i in strs[1::]:
if i[n]==temp:
continue
else:
flag=1
break
if flag!=1:
t+=temp
return t
另一个思路:取第一个字符串并与接下来的字符串循环对比,利用find()匹配查找,若返回索引不为0则去掉待匹配字符串最后一个字母,直到为空。运行时间和内存消耗都更优!
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ""
prefix = strs[0]
for s in strs[1:]:
while s.find(prefix) != 0:
prefix = prefix[0:len(prefix) - 1]
if prefix == "":
return prefix
return prefix
常规思路:
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len (strs) == 1:
return strs[0]
if strs == []:
return ""
temp = self.__firstmatch(strs[0],strs[1])
if temp =="":
return ""
result = temp
for i in range(len(strs)-1):
temp = self.__firstmatch(temp,strs[i+1])
if temp =="":
return ""
if len (temp)<len(result):
result = temp
return result
def __firstmatch(self,a,b):
result=""
for i in range(len(a)):
if i>len(b)-1 or a[i] != b[i] or i>len(b) :
break
result +=a[i]
return result
- 三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组
思路:通过先对list进行排序,后遍历所有满足要求的三元组,只是在避免三元组重复的问题上,使用了字典作为判断条件。具体思路是将所有符合要求的三元组的最大值和最小值组合成元组,将这个元组作为key保存在字典中,根据字典的key的唯一性,就可保证三元组的唯一性。
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
list_ret = []
d = {}
num = len(nums)
nums.sort()
for i in range(num):
if i == 0 or nums[i]>nums[i-1]: ##避免出现重复三元组
l = i+1
r = num-1
while(l < r):
s = nums[i] + nums[l] + nums[r]
if s == 0:
col = [nums[i],nums[l],nums[r]]
max_e = max(col)
min_e = min(col)
if((max_e,min_e) not in d):
list_ret.append(col)
d[(max_e,min_e)] = 1 ###字典用来最终避免三元组重复
r -= 1
l += 1
elif s > 0:
r -= 1
else:
l += 1
return list_ret
借鉴了好多人的解题思路,进行了尝试。算法小白在龟速学习中,非原创。特此感谢!