leetcode easy problems

1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dic = {}
        for index, value in enumerate(nums):
            sub = target - value
            if sub in dic:
               return [dic[sub], index]
            else:
               dic[value] = index

需要返回索引,关键在于创建字典,键是数组里的元素,值是索引,方便查找。
题目给的target输入一般就是nums里面两个数的值,只要遍历数组,找到对应索引即可,最快的是一边遍历一边添加字典,比较笨的做法是先生成整个字典。

7 . Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        revx=int(str(abs(x))[::-1])
        if revx>2**31:
            return 0
        if x<0:
            return revx*(-1)
        else:
            return revx
        

分片[::-1]简单

注意大数

9. Palindrome Number

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x<0:
           return False
        a=x
        b=0
        while x>0:
           b=b*10+x%10
           x//=10
        if a==b:
           return True
        else:
           return False

回文,每次获得一个个位数,先×10加上个位数,循环

13. Roman to Integer

Roman numerals are represented by seven different symbols:  I , V , X , L , C , D and M .

For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
        a=0
        size=len(s)
        i=1
        while i<size:
            if dic[s[i]]>dic[s[i-1]]:
                a=a+dic[s[i]]-dic[s[i-1]]
                i+=1
            else:
                a = a + dic[s[i - 1]]
            i+=1
        if dic[s[size-1]]<=dic[s[size-2]]:
            a=a+dic[s[size-1]]
        return a

关键:字典+根据字符串 索引获得 ,从而可以比较前后两个数的
14 . Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ''
        size=len(strs)
        l=[0 for i in range(size)]
        for i in range(size):
            l[i]=len(strs[i])
        s=sorted(l)[0]
        i=0
        str=''
        flag=1
        while i<s:
            for j in range(1,len(strs)):
                if strs[0][i] != strs[j][i]:
                    flag=0#应该直接返回,因为不需要执行别的语句
                    break
            if flag==1:
                str=str+strs[0][i]
            i+=1
        return str
第一次写太繁琐,虽然时间是一样的。

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ''
        str=''
        for i in range(len(strs[0])):
            for j in range(1,len(strs)):
                if i >= len(strs[j]) or strs[j][i] != strs[0][i]:
                    return str
            str=str+strs[0][i]
        return str
注意点:字符串列表如果为空直接返回,否则输出会多个[]
             字符串连接直接用+号

20. Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if not s:
            return True
        def Symmetrical(a,b):
            if a=='[' and b==']':
                return 1
            if a=='{' and b=='}':
                return 1
            if a=='(' and b==')':
                return 1
            else:
                return 0
        size=len(s)
        flag=0
        if size%2!=0:
            return False
        else:
            for i in range(size//2):
                flag=0
                if s[i] in ['[','{','(']:
                    for j in range(1,size):
                        if Symmetrical(s[i],s[j])==1 and (j-i)%2==1:
                           flag=1
                    if flag==0:
                        return False
                else:
                    for j in range(i):
                        if Symmetrical(s[j],s[i])==1 and (i-j)%2==1:
                            flag=1
                    if flag==0:
                        return False
            return True

第一次写,傻傻地考虑了各种测试例子,总结起来就是左匹配右匹配,但是如果输入一个相当长的数组就TLE了!!
后来,突然想到之前数据结构做过这题,应该用栈就简单了啊!(看来还是得按tag来
class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if not s:
            return True
        size=len(s)
        stack=[' 'for i in range(size)]
        top=-1
        index=0
        while index<size:
            if s[index]==')':
                if top>=0 and stack[top]=='(':#如果栈里有元素且可以匹配,出栈
                    top-=1
                else:
                    return False
            elif s[index]=='}':
                if top>=0 and stack[top]=='{':
                    top-=1
                else:
                    return False
            elif s[index]==']':
                if top>=0 and stack[top]=='[':
                    top-=1
                else:
                    return False
            else:#左括号的都进栈,等待被匹配
                top+=1
                stack[top]=s[index]
            index+=1
        if top==-1 and index==size:
            return True
        else:
            return False
注意if和elif区别,
若全部用if语句,程序运行时会遍历所有if。而用if-elif,程序运行时,只要if或后续某一个elif之一满足逻辑值为True,则程序执行完对应输出语句后自动结束该轮if-elif(即不会再去冗余地执行后续的elif或else)。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值