• 2023.10.19


    2905. 找出满足差值条件的下标 II

    提示

    中等

    13

    相关企业

    给你一个下标从 0 开始、长度为 n 的整数数组 nums ,以及整数 indexDifference 和整数 valueDifference 。

    你的任务是从范围 [0, n - 1] 内找出  2 个满足下述所有条件的下标 i 和 j :

    • abs(i - j) >= indexDifference 且
    • abs(nums[i] - nums[j]) >= valueDifference

    返回整数数组 answer。如果存在满足题目要求的两个下标,则 answer = [i, j] ;否则,answer = [-1, -1] 。如果存在多组可供选择的下标对,只需要返回其中任意一组即可。

    注意:i 和 j 可能 相等 。

    示例 1:

    输入:nums = [5,1,4,1], indexDifference = 2, valueDifference = 4
    输出:[0,3]
    解释:在示例中,可以选择 i = 0 和 j = 3 。
    abs(0 - 3) >= 2 且 abs(nums[0] - nums[3]) >= 4 。
    因此,[0,3] 是一个符合题目要求的答案。
    [3,0] 也是符合题目要求的答案。
    

    示例 2:

    输入:nums = [2,1], indexDifference = 0, valueDifference = 0
    输出:[0,0]
    解释:
    在示例中,可以选择 i = 0 和 j = 0 。 
    abs(0 - 0) >= 0 且 abs(nums[0] - nums[0]) >= 0 。 
    因此,[0,0] 是一个符合题目要求的答案。 
    [0,1]、[1,0] 和 [1,1] 也是符合题目要求的答案。 
    

    示例 3:

    输入:nums = [1,2,3], indexDifference = 2, valueDifference = 4
    输出:[-1,-1]
    解释:在示例中,可以证明无法找出 2 个满足所有条件的下标。
    因此,返回 [-1,-1] 。

    提示:

    • 1 <= n == nums.length <= 105
    • 0 <= nums[i] <= 109
    • 0 <= indexDifference <= 105
    • 0 <= valueDifference <= 109
    1. class Solution {
    2. public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {
    3. int ans[]={-1,-1};
    4. int maxIndex=0;
    5. int minIndex=0;
    6. for(int j=indexDifference;j
    7. int i=j-indexDifference;
    8. if(nums[i]>nums[maxIndex]){
    9. maxIndex=i;
    10. }else if(nums[i]
    11. minIndex=i;
    12. }
    13. if(nums[maxIndex]-nums[j]>=valueDifference){
    14. return new int[]{maxIndex,j};
    15. }
    16. if(nums[j]-nums[minIndex]>=valueDifference){
    17. return new int[]{minIndex,j};
    18. }
    19. }
    20. return ans;
    21. }
    22. }

    这个题,首先是

    abs(i - j) >= indexDifference

    条件,意味着j到i的距离要>=indexDifference,意味着我们遍历的时候,j可以直接从j=indexDifference开始遍历,i=j-indexDifference就可以了

    然后是这个abs(nums[i] - nums[j]) >= valueDifference

    条件,我们可以才分为两个子条件

    nums[maxIndex]-num[i]>=valueDifference

    num[i]-numx[minIndex]>=valueDifference

    只要是满足这两个条件就是符合答案的数据

  • 相关阅读:
    字节跳动面试笔试总结——算法岗位
    物通博联“5G+IIOT”构建污水处理物联网,助力远程监控智慧管理
    github网站打不开,hosts文件配置
    单例模式(Singleton)
    开发累了就摸个鱼,帮我修改一下中式英语
    一款.NET开源、免费、实用的多功能原神工具箱(改善桌面端玩家的游戏体验)
    【linux】进程创建,进程终止
    不同的时钟机制
    LeetCode --- 2. Add Two Numbers 解题报告
    HTML中的<img>标签使用指南
  • 原文地址:https://blog.csdn.net/m0_73035591/article/details/133926748