LeetCode_220

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3, t = 0
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1, t = 2
Output: true

Example 3:

Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false

暴力是個好方法。But 我們遇到問題就使用暴力,會導時間複雜度很高。本體使用暴力很容易解決,具體代碼如下:

public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        //思路:使用暴力方法
        //雙層遍歷,第一層使用控制k,使K逐漸減少。第二層遍歷數組,用i和j對應的數據相減與t比較
        while (k > 0) {
            for (int i = 0; i < nums.length; i++) {
                if ((i + k) < nums.length){
                    if ((nums[i+k] - nums[i]) <= t){
                        return true;
                    }
                }
            }
            k --;
        }
        return false;
    }

上面算法的時間複雜度是O(n^2),努力的人怎麼能止步於此呢?下面還有一個算法可以在O(n)的時間複雜度之內實現。

思路介紹:

假設我們的輸入是:

nums = [1, 5, 17, 6, 8], t = 2, k = 5 

我們根據 t 來劃分窗口,每個窗口的大小是 t + 1 。創建一個窗口數組windows,我們使用windows[ 0 ] 來儲存[0, 1, 2],windows[ 1 ] 來儲存[3, 4, 5],以此類推。這樣儲存可以保證同一個窗口內的數據最大差異小於 t 。3 - 2 = 1,3 在窗口 1 中,2 在窗口 0 中,因此相鄰的窗口有可能出現符合條件的值。但是6 - 2 = 4,相間隔的窗口不可能出現符合條件的值。因此接下來我們把每個數字壓入窗口。

1 / 3 = 0 將 2 壓入窗口 0,並與相鄰的窗口 1 進行比較。窗口 1 沒有值,我們繼續;

5 / 3 = 1 將 5 壓入窗口 1,並與相鄰的窗口 0 和窗口 2 進行比較。5 - 1 = 4 > 2並且窗口 2 沒有值,我們繼續;

17 / 3 = 5 將 17 壓入窗口 5,並與相鄰的窗口 4 和窗口 6 進行比較。窗口 4 和窗口 6 沒有值,我們繼續;

6 / 3 = 2 將 6 壓入窗口 2,並與相鄰的窗口 1 和窗口 3 進行比較。6 - 5 = 1 符合條件,結束;

這裏還有一個結束條件,就是兩個數字同時進入同一個窗口(我們設計的時候就使同一個窗口內最大差異小於等於 t ),這也是觸發結束的條件。

如果我們添加了k個數字之後,要刪除最先加入的那個。因爲規定好了要在 k 個數內找符合條件的值。

具體代碼:

if (nums == null || k < 0 || t < 0){
            return false;
        }
        int key, value;
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            key = nums[i] / (t + 1);
            value = nums[i];
            if (map.containsKey(key)){
                return true;
            }else {
                map.put(key, value);
                if(map.get(key - 1) != null && Math.abs(nums[i] - map.get(key - 1)) <= t) return true;
                if(map.get(key + 1) != null && Math.abs(nums[i] - map.get(key + 1)) <= t) return true;
                if (map.size() > k){
                    map.remove(Math.floorDiv(nums[i - k], (long) t + 1));
                }
            }
        }
        return false;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章