前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 1855. Maximum Distance Between a Pair of Values

Leetcode 1855. Maximum Distance Between a Pair of Values

作者头像
Tyan
发布2021-07-29 12:10:55
3460
发布2021-07-29 12:10:55
举报
文章被收录于专栏:SnailTyanSnailTyan

1. Description

Maximum Distance Between a Pair of Values
Maximum Distance Between a Pair of Values

2. Solution

**解析:**Version 1,由于两个数组都是非增数组,因此保证了数值的大小关系,如果i<=j,此时比较nums1[i] <= nums2[j],如果符合,则计算距离distance,并与已有距离比较取较大值,在i<=jnums1[i] > nums2[j]的情况下,此时应该移动i,如果i>j,则移动j,由于保证了大小关系,因此只要遍历完一个数组即可。Version 2是对Version 1的进一步优化。

  • Version 1
代码语言:javascript
复制
class Solution:
    def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
        distance = 0
        i = 0
        j = 0
        while i < len(nums1) and j < len(nums2):
            if i <= j:
                if nums1[i] <= nums2[j]:
                    distance = max(distance, j - i)
                    j += 1
                else:
                    i += 1
            else:
                j += 1
        return distance
  • Version 2
代码语言:javascript
复制
class Solution:
    def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
        distance = 0
        i = 0
        j = 0
        while i < len(nums1) and j < len(nums2):
            if nums1[i] > nums2[j]:
                i += 1
            else:
                distance = max(distance, j - i)
                j += 1
        return distance

Reference

  1. https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-07-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. Description
  • 2. Solution
  • Reference
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档