1.给定一个整数数组 nums
和一个目标值 target
,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
计算:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
方法一:(5848 ms) class Solution: def twoSum(self, nums, target): a=[] length=len(nums) for i in range(0,length-1): for j in range(i+1,length): if(nums[i]+nums[j]==target): return [i,j] 方法二:(48 ms) class Solution: def twoSum(self, nums, target): a=[] length=len(nums) for i in range(0,length-1): for j in range(i+1,length): if(nums[i]+nums[j]==target): return [i,j] 方法三:(1152 ms) class Solution: def twoSum(self, nums, target): length=len(nums) dict={} for i in range(length): var=target-nums[i] if var in nums and i!=nums.index(var): return [i,nums.index(var)]
2.计算最长回文字串
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
def longestPalindrome( s): if len(s) < 2 or s == s[::-1]: return s n = len(s) # 定义起始索引和最大回文串长度,odd奇,even偶 start, maxlen = 0, 1 # 因为i=0的话必然是不可能会有超过maxlen情况出现,所以直接从1开始 for i in range(1, n): # 取i及i前面的maxlen+2个字符 odd = s[i - maxlen - 1:i + 1] # len(odd)=maxlen+2 # 取i及i前面的maxlen+1个字符 even = s[i - maxlen:i + 1] # len(even)=maxlen+1 print("i="+str(i)+";\t"+"maxlen="+str(maxlen)+";\todd="+odd+";"+"\t"+"even="+even) if i - maxlen - 1 >= 0 and odd == odd[::-1]: start = i - maxlen - 1 maxlen += 2 continue if i - maxlen >= 0 and even == even[::-1]: start = i - maxlen maxlen += 1 #print(s[start:start + maxlen]) return s[start:start + maxlen] s="abaqw" # b=s[-1:2] # print(b) a=longestPalindrome(s) print(a)