Leetcode 学习计划之21天算法 (二)

第2天 双指针

双指针包括对撞指针和快慢指针。

 题目要求对数组原地操作,或O(1)空间复杂度时可考虑此法。

在涉及到调换位置做移动时均可考虑双指针,相邻两个位置做交换、头尾交换、相隔交换均可。

对撞指针的伪代码:

function fn (list) {
  var left = 0;
  var right = list.length - 1;

  //遍历数组
  while (left <= right) {
    left++;
    // 一些条件判断 和处理
    ... ...
    right--;
  }
}

977.有序数组的平方

1、可直接先平方,再排序

2、可用双指针判断 开辟一个新数组,最大值肯定在两侧,右侧大,就可以赋值给新数组的右边,右边的指针向左移;左侧大,就把左侧的赋值给新数组的右边,左指针右移。

class Solution(object):
    def sortedSquares(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        l = len(nums)
        ans = [0] * l
        left = 0
        right = l-1
        l = right
        while(left<=right):
            le = nums[left]**2
            ri = nums[right]**2
            if le<=ri:
                ans[l] = ri
                right-=1
            else:
                ans[l] = le
                left+=1
            l-=1
        return ans

 189.轮转数组

1、可以直接用数组的切片交换

2、可以用数组反转,先整个反转,再把左边k个反转,再反转右边的其余的

反转操作可以利用双(对撞)指针进行。还有切片的nums[::-1]也可实现反转操作。

class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        l = len(nums)
        k = k%l
        index = l - k
        ans = [0]*k
        ans = nums[index:]
        nums[k:l] = nums[0:index]
        nums[0:k] = ans
class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        l = len(nums)
        k = k%l
        index = l - k
        nums[0:] = nums[index:] + nums[0:index]
class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        def swap(nums):
            l = 0
            r = len(nums)-1
            while(l<=r):
                nums[l],nums[r] = nums[r],nums[l]
                l+=1
                r-=1
            return nums

        l = len(nums)
        k = k%l
        index = l - k
        nums[:] = nums[::-1]
        nums[:k] = swap(nums[0:k])
        nums[k:] = swap(nums[k:])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值