leetcode 1-100 easy难度题目汇总

主要是考虑到easy题目没什么好分析的, 故统一总结在一篇文章里. 留作记录.

收录leetcode1-100题中easy难度的题目. 带星号的表示经典题型, 或者有衍生题.

1. Two Sum (Easy)

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        sum = []
        i = 0
        while i < len(nums) :
            try:
                j = nums.index(target-nums[i])
            except ValueError,e:
                pass
            else: 
                if i!=j:
                    sum.extend([i,j])
                    return sum
            finally:
                i +=1 

7. Reverse Integer (Easy)

# integer has a range.Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31,  2^31 − 1].
class Solution:
    def reverse(self, x: int) -> int:
        if x == 0:
            return 0
        if x > 0:
            s = str(x)
            s = int(s[::-1])
        else:
            s = str(x)[1:]
            s = -int(s[::-1])
        if s > 2**31 - 1 or s < -(2**31):
            return 0
        return s

9. Palindrome Number (Easy)

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0:
            return False
        x = str(x)
        if x == x[::-1]:
            return True
        else:
            return False

13. Roman to Integer (Easy)

https://leetcode.com/problems/roman-to-integer/
题目描述

把罗马字母转换成整型数字.

"""
前面的罗马字符后面如果小于后面的罗马字符, 结果非但不能加上前面的罗马字, 还要减去它. 
所以num -= 2*pre. 如果前面的罗马字符大于后面的, 则可以直接加上后面的.
"""
class Solution:
    def romanToInt(self, s: str) -> int:
        value_roman = {
   "M":1000, "D":500, "C":100, "L":50, "X":10, "V":5, "I":1}
        pre = 0
        num = 0
        for i in s:
            num += value_roman[i]
            if value_roman[i] > pre:
                num -= 2 * pre
            pre = value_roman[i]
        return num

14. Longest Common Prefix (Easy)

https://leetcode.com/problems/longest-common-prefix/
题目描述

给定一个字符串数组, 输出最大共同前缀
Input: [“flower”,“flow”,“flight”]
Output: “fl”

"""
从头遍历所有字符串, 直到不一样的字符出现.
"""
class Solution:
    def longestCommonPrefix
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值