leetcode lintcode python

目录

1.Two Sum(Hash Table)

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.

Given nums=[2,7,11,15],target=[9],
Because nums[0]+nums[1]=2+7=9,
return [0,1]

hash表,通过判断target-当前的数的值是否在hash表中

def twoSum(nums,target):
    hash={}
    for i in range(len(nums)):
        if target-nums[i] not in hash:
            hash[nums[i]]=i
        else:
            return [dict[target-nums[i]],i]

def twoSum(nums,target):
    result=[]
    for i in range(len(nums)):
        for j in range(i+1,len(nums)):
            if nums[i]+nums[j]==target:
                result.append(i)
                result.append(j)
                return result

可以看出 hash表可以提高速度

9.回文数

输入:x = 121
输出:true
输入:x = -121
输出:false
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
输入:x = -121
输出:false
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x<0 or(x%10==0 and x!=0):
            return False
        rever=0
        while(x>rever):
            rever=rever*10+x%10
            #取商
            x=x//10
        return x==rever or x==rever//10

14.最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀

输入:strs = ["flower","flow","flight"]
输出:"fl"
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        res=""
        for tmp in zip(*strs):
            s=set(tmp)
            if(len(s)==1):
                res+=tmp[0]
            else:
                break
        return res
            
                

15.三数之和

「不重复」的本质是什么?我们保持三重循环的大框架不变,只需要保证:

第二重循环枚举到的元素不小于当前第一重循环枚举到的元素;

第三重循环枚举到的元素不小于当前第二重循环枚举到的元素。

20.Valid Parentheses有效的括号(stack)

Given a string containing just the characters '('  ')'  '{'   '}'  '['   ']', 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.

"([)]"
false
#1.当遍历完字符串后栈不为空,则说明有多余的左括号,
#2.当遍历过程中遇到右括号时栈为空,则说明右括号多余,
#3.当遍历过程中遇到右括号时,栈顶元素与之不对应,则说明括号的类型没有对应上

class Solution:
    def isValid(self, s: str) -> bool:
        hash={')':'(','}':'{',']':'['}
        stack=[]  
        for char in s:
            if char not in hash:
                stack.append(char)
            else:
                #如果栈为空,即情况2 or 栈顶元素不对应 即类型3
                if not stack or stack[-1]!= hash[char]:
                    return False
                stack.pop()
        #如果栈为空 return true ,or return false 
        return not stack

#2
class Solution:
    def isValid(self, s: str) -> bool:
        dict={'(':')','{':'}','[':']'}
        record=[]
        for c in s:
            if c=='(':
                record.append('(')
            elif c=='[':
                record.append('[')
            elif c=='{':
                record.append('{')
            else:
                if record:
                    out=record.pop()
                    if dict[out]!= c:
                        return False
                else:
                    return False
        if record==[]:
            return True
        else :
            return False

            

       

22.Generate Parentheses(括号生成)

Given n pairs of parentheses,write a function to generate all combinations of well-formed parentheses.

输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
输入:n = 1
输出:["()"]

35.搜索插入位置

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        left,right=0,len(nums)-1
        while(left<=right):
            middle=(right+left)//2
            if nums[middle]>target:
                right=middle-1
            elif nums[middle]<target:
                left=middle+1
            else:
                return middle
        #如果不存在
        return left



42.接雨水

class Solution:
    def trap(self, height: List[int]) -> int:
        if not height:
            return 0
        
        n = len(height)
        leftMax = [height[0]] &
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值