leetcode刷题笔记---2

题目: 搜索插入位置(两种方法)

def searchInsert1(nums, target):

    nums.append(target)
    nums.sort()   # 全部插进去进行排序,再循环判断
    for ind, values in enumerate(nums):
        if values == target:
            return ind
            break

import math
def searchInsert2( nums, target):
    left, right = 0, len(nums) - 1
    while left <= right:
        mid = left + math.ceil((right - left) / 2)   # 利用二分法查找
        if nums[mid] >= target:
            right = mid - 1
        else:
            left = mid + 1
    return left
namelist = [1,5,8,7,3,4]
target = 5
print(searchInsert1(nums=namelist,target=target))
print(searchInsert2(nums=namelist,target=target))
得出结果:3

题目: 最后一个单词的长度

def lengthOfLastWord(S):
    if(S.split()): # 确定字符非空
        return len(S.split()[-1]) # 非空字符串切割取最后一个
    else:
        return 0
string1 =' '
string2 ='ywfd vcvdj vsdv asasc '
print(lengthOfLastWord(string1))
print(lengthOfLastWord(string2))

得到的结果: 0 以及5


题目:罗马数字转整数 

def transform_roman_num2_alabo(s):
    '''''
    将罗马数字转化为阿拉伯数字
    '''
    numeral_map = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
    decimal = 0
    for i in range(len(s)):  # 一次迭代循环
        m = numeral_map[s[i]]
        n = numeral_map[s[i-1]]
        if i > 0 and m > n: # 判断前values是否大于后values,Yes情况 加上前values-2*values
            decimal += m - 2 * n
        else:               # NO情况直接加上后values
            decimal += m
    return decimal
string = "MCMV"
print(transform_roman_num2_alabo(string))

得到结果:1905


平方数之和 

给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c,有即返回True,否则False

import math
def fun1(c):
    for a in range(int(math.sqrt(c)) + 1):
        b = int(math.sqrt(c - a ** 2))    # 这里避免for 循环,直接做减法进行判断一下
        if a ** 2 + b ** 2 == c:
            return True
    return False
print(fun1(10))

得到的结果: True


你可能感兴趣的:(leetcode,leetcode)