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]

leetcode lintcode python_第1张图片

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.最长公共前缀

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

leetcode lintcode python_第2张图片

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

leetcode lintcode python_第3张图片

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.三数之和

leetcode lintcode python_第4张图片

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

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

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

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]

42.接雨水

leetcode lintcode python_第5张图片

leetcode lintcode python_第6张图片

class Solution:
    def trap(self, height: List[int]) -> int:
        if not height:
            return 0
        
  

你可能感兴趣的:(算法,leetcode,哈希算法,散列表)