随笔-数组中两个不同元素的比较

版权声明:中华人民共和国持有版权 https://blog.csdn.net/Fly_Fly_Zhang/article/details/84965424

题目:

给定一个整数数组,判断数组中是否有两个不同的索引 i 和 j,使得 nums [i] 和 nums [j] 的差的绝对值最大为 t,并且 i 和 j 之间的差的绝对值最大为 ķ。

示例 1:

输入: nums = [1,2,3,1], k = 3, t = 0
输出: true
示例 2:

输入: nums = [1,0,1,1], k = 1, t = 2
输出: true
示例 3:

输入: nums = [1,5,9,1,5,9], k = 2, t = 3
输出: false

思路:有一个坑就是要类型转换,两个int 的值相加或者相减,其值可能会超出int 的取值范围; 还有就是用到一个数学方法:Math.abs() ; 取绝对值;

class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if(nums.length<=1){
            return false;
        }
        int j;
        for(int i=0;i<nums.length-1;i++){
               j=i+1;
            while(j<nums.length&&j-i<=k){
                 long l1=nums[i];
                 long l2=nums[j];
               //if(l1-l2<=t && l1-l2>=-t  ){   //测试时,这个判断语句运行超慢;
               if(Math.abs(l1-l2)<=t){
                    return true;
                }
                j++;
            }
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/Fly_Fly_Zhang/article/details/84965424