双指针

目录:

  1. Two Sum II
  2. Sort Colors
  3. 盛最多水的容器

知识点:双指针主要用于遍历数组,两个指针指向不同的元素,从而协同完成任务。

167. Two Sum II - Input array is sorted

class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        start=0
        end=len(numbers)-1
        while start<end:
            if numbers[start]+numbers[end]==target:
                return start+1,end+1
            if numbers[start]+numbers[end]<target:
                start+=1
            else:
                end-=1
        return None

75. Sort Colors

荷兰国旗问题:

解题思路:创建一个head 和tail指针指向数组的头和尾,遍历数组,如果是0则和head 指向的元素交换;如果是1则和tail指针指向的元素交换。同时移动相应的指针位置。

代码:

class Solution(object):
    def sortColors(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        
        head,cur,tail=0,0,len(nums)-1
        while cur <= tail:
            if nums[cur]==0:
                nums[head],nums[cur]=nums[cur],nums[head]
                head+=1
                cur+=1
            elif nums[cur]==2:
                nums[cur],nums[tail]=nums[tail],nums[cur]
                tail-=1
            else:
                cur+=1
        return nums

11. 盛最多水的容器

代码:

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        left = 0
        right = len(height) - 1
        maxArea = 0
        while left < right:
            b = right - left
            if height[left] < height[right]:
                h = height[left]
                left += 1
            else:
                h = height[right]
                right -= 1
            area = b*h
            if maxArea < area:
                maxArea = area
        return maxArea
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值