zoukankan      html  css  js  c++  java
  • 双指针算法

    1、无重复最长子字符串

    题目:

    解法:

    class Solution:
        def lengthOfLongestSubstring(self, s):
            """
            :type s: str
            :rtype: int
            """
            if s=='':return 0
            dic = {}
            i,j = 0,0
            max = 0
            while j < len(s) :
                if s[j] in dic  and dic[s[j]]>=i:
                    if max<= j-i:max = j-i
                    if j==len(s)-1:return max
                    i = dic[s[j]] +1
                dic[s[j]] = j
                j += 1
                if j == len(s) : return max if max>j-i else j-i

    2、盛最多水的容器

    解法:

    class Solution:
        def maxArea(self, height):
            """
            :type height: List[int]
            :rtype: int
            """
            left = 0
            right = len(height)-1
            maxarea = 0
            while right>left:
                if height[left]<height[right]:
                    area = height[left]*(right-left)
                    left +=1
                else:
                    area = height[right] * (right - left)
                    right-=1
                if area >maxarea:
                    maxarea = area
            return maxarea

    3、三数之和

    对于寻找两个数的和,我们通常采用首尾双指针的处理方法,即对于排序后的数组(升序)而言,分别从头尾向中间靠拢,当头尾指针对应元素之和大于目标值时,我们需要缩小元素和,即尾指针前移。当元素之和小于目标值时,我们需要增大元素和,即头指针后移。当头尾指针相遇时,程序终止。

    而这道题三个数之和,也可以采用相同的思想,先”固定”第一个数,从后面的子数组中找另外两个数的和。也就是说我们只要在找两数和的前提下,外层嵌套一层遍历第一个数的循环就可以了。

    当然,也需要处理重复元素的问题。

    解法:

    def f(nums):
        dic = {}
        ret = []
        for i in nums:
            if i in dic:
                dic[i]+=1
            else:
                dic[i]=1
        if 0 in dic and dic[0]>=3:ret.append([0,0,0])
        for i in dic:
            if dic[i]>=2 and i!=0:
                if 0-2*i in dic:
                    ret.append([i,i,0-2*i])
        ls = sorted(list(dic))
        length = len(ls)
        for i in range(length):
            head = i+1
            tail = length-1
            while head<tail:
                result = ls[head]+ls[tail]
                if result==-ls[i]:
                    ret.append([ls[i],ls[head],ls[tail]])
                    head+=1
                    tail-=1
                elif result<-ls[i]:
                    head+=1
                else:
                    tail-=1
        return ret

    大神解法:

    class Solution:
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            import collections
            
            d = collections.Counter(nums)
            nums_keys = d.keys()
            
            
            pos, neg = [],[]
            
            for p in nums_keys:
                if p >= 0:
                    pos.append(p)
                else:
                    neg.append(p)
                    
            r = []
            
            if d.get(0,0) > 2:
                r.append([0,0,0])
            
            for i in neg:
                for j in pos:
                    tar = - i - j
                    if tar in nums_keys:
                        if i< tar < j:
                            r.append([i,tar,j])
                        elif (j==tar or i == tar) and d[tar]>1:
                            r.append([i,tar,j])
            return r

     4。最接近的三数和

    原理同上,用双指针法:

    class Solution:
        def threeSumClosest(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: int
            """
            nums.sort()
            l = len(nums)
            ret = 10000000
            for i in range(l):
                head = i+1
                tail = l-1
                while head<tail:
                    result = nums[i]+nums[head]+nums[tail]
                    if result==target:return target
                    elif result<target:
                        head+=1
                    else:
                        tail-=1
                    if abs(result-target)<abs(target-ret):
                        ret = result
            return ret
    View Code
  • 相关阅读:
    第二阶段冲刺第1天
    每周总结(5.30)
    每周总结(5.23)
    个人作业——顶会热词进程2.3
    个人作业——顶会热词进程2.2
    c#日期相关代码
    Linux服务器安装mysql
    Linux运行yum时出现/var/run/yum.pid已被锁定,PID为xxxx的另一个程序正在运行的问题解决
    【转】火狐浏览器js转换日期问题
    docker流程
  • 原文地址:https://www.cnblogs.com/linshuhui/p/9621653.html
Copyright © 2011-2022 走看看