【打卡】数组的最长前缀

描述
给定两个正整数X和Y,以及正整数数组nums。
我们需要找到一个最大的index,使得在nums[0], nums[1], … , nums[index]中,出现X、Y的次数相等,且至少均出现一次,返回该index。
若不存在这样的index,则返回-1。

示例 1:

输入:
X = 2
Y = 4
nums: [1, 2, 3, 4, 4, 3]
输出: 3
解释: 保证 2 和 4 出现相同次数的最长前缀是: {1, 2, 3, 4},所以你应该返回3。

示例 2:

输入:
X = 7
Y = 42
nums = [7、42、5、6、42、8、7、5、3、6、7]
输出:9
解释:保证7和42出现相同次数的最长前缀是:{7, 42, 5, 6, 42, 8, 7, 5, 3, 6},所以你应该返回9。

示例 3:

输入:
X = 1
Y = 10
nums:  [2, 3, 1]
输出:-1
解释:不存在前缀使得 1 和 10 都出现且出现次数相同的情况
from typing import (
    List,
)

class Solution:
    """
    @param x: a integer
    @param y: a integer
    @param nums: a list of integer
    @return: return the maximum index of largest prefix
    """
    def longest_prefix(self, x: int, y: int, nums: List[int]) -> int:
        # write your code here
        l = len(nums)
        icount = 0
        jcount = 0
        result = -1
        if not nums:
            return -1
        for i in range(l):
            if nums[i] == x:
                icount += 1
            if nums[i] == y:
                jcount += 1
            if icount != 0 and icount == jcount:
                result = i
        return result
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dataloading...

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值