下面题目都来自于LeetCode.
##第一题[选自Array类别]
解题思路:
这道题目相当容易,因为Python中提供了index()函数——如果某个元素存在于列表中,返回其在列表中的位置。如此一来,target在nums中的情况便解决了。
接下来是target不在nums中的情况。遍历一下nums中的变量,用一个变量 i 记录当前访问的列表下标。如果访问的元素num的值比target大,则说明tartget应该插入的位置在后面,所以更新 i 的值(i=i+1);如果
访问的元素num的值小于或等于target的值,则说明tartget应该插入的位置就是当前的位置。最后,如果遍历一遍列表nums后函数还没返回,说明tartget的值比nums中所有元素的值都大,应该插入的位置是nums最后一位的后一位,即 len(nums) + 1.
代码如下:
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target in nums:
return nums.index(target)
else:
i = 0
for num in nums:
if target > num:
i = i + 1
else:
return i
return len(nums)
##第二题
解题思路:
从最后一位开始判断,先用 i 记录不是空格字符的元素的最大下标,然后从该位置开始往前扫描,用ans记录单词中字母的数量,扫描到空格时停止运算,返回ans。另外,这个算法对于没有单词的情况需要特判一下。
代码如下:
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
i = len(s)-1
ans = 0
j = i
while i >= 0:
if s[i] != ' ':
break
else:
i = i-1
if i < 0:
return 0
while i >= 0:
if s[i] == ' ':
break
else:
ans = ans + 1
i = i - 1
return ans
##第三题
解题思路:
只需要把数字转换成字符串类型再转换成list类型,再对其使用reverse后与使用前的list进行对比,即可得到答案。
代码如下:
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
a = list(str(x))
b = list(str(x))
b.reverse()
if a == b:
return True
else:
return False