Contains Duplicate III_C

來源:互聯網
上載者:User
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.

解題思路:

給定一個整數數組,判斷其中是否存在兩個不同的下標i和j滿足:| nums[i] - nums[j] | <= t 並且 | i - j | <= k。


如果: | nums[i] - nums[j] | <= t   式a等價: | nums[i] / t - nums[j] / t | <= 1   式b推出: | floor(nums[i] / t) - floor(nums[j] / t) | <= 1   式c?等價: floor(nums[j] / t) ∈ {floor(nums[i] / t) - 1, floor(nums[i] / t), floor(nums[i] / t) + 1} 式d

其中式b是式c的充分非必要條件,因為逆否命題與原命題等價,所以:

如果: floor(nums[j] / t) ? {floor(nums[i] / t) - 1, floor(nums[i] / t), floor(nums[i] / t) + 1} 非d推出: | nums[i] - nums[j] | > t   非a

用一個hash表來儲存滑動視窗的數值,其中索引值為nums[i]/t,對於數值nums[k],若存在鍵為nums[k]/t,nums[k]/t-1,nums[k]/t+1,再比較他們的數值。

有兩個地方需要注意:

1、該題目可能會int類型溢出,因此需要先轉化成long long類型。

2、map和unordered_map並不是按插入順序排序的。因此還需要用一個隊列來維持一個滑動視窗。

下面是C++代碼:

class Solution {public:    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {        if(k<1||t<0){            return false;        }        unordered_map<int, long long> nums_map;        queue<int> keys;     //順序儲存的一些索引值        int len = nums.size();        for(int i=0; i<len; i++){            int key = nums[i]/max(t, 1);            for(int j=key-1; j<=key+1; j++){                if(nums_map.find(j)!=nums_map.end() && abs(nums_map[j] - nums[i])<=(long long)t){                    return true;                }            }            nums_map[key]=nums[i];            keys.push(key);            if(nums_map.size()>k){                nums_map.erase(keys.front());                keys.pop();            }        }        return false;    }};


參考連結:http://bookshadow.com/weblog/2015/06/03/leetcode-contains-duplicate-iii/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.