public class DayCode {    public static void main(String[] args) {        int[] nums = new int[]{1,2,2,3,1,4,2};        int limit = 2;        int ans = new DayCode().longestSubarray(nums, limit);        System.out.println("ans is " + ans);    }
    /**     * https://leetcode-cn.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/     * 时间复杂度 O(n log n)     * 空间复杂度 O(n)     * @param nums     * @param limit     * @return     */    public int longestSubarray(int[] nums, int limit) {        TreeMap<Integer, Integer> map = new TreeMap<>();        int n = nums.length;        int left = 0;        int right = 0;        int ans = 0;        while (right < n) {            map.put(nums[right], map.getOrDefault(nums[right], 0) + 1);            while (map.lastKey() - map.firstKey() > limit) {                map.put(nums[left], map.get(nums[left]) - 1);                if (map.get(nums[left]) == 0) {                    map.remove(nums[left]);                }                left++;            }            ans = Math.max(ans, right - left + 1);            right++;        }
        return ans;    }}
评论