1. 程式人生 > >leetcode筆記:Contains Duplicate III

leetcode筆記:Contains Duplicate III

一. 題目描述

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.

二. 題目分析

題目大意是,給定一個整數陣列,判斷其中是否存在兩個不同的下標ij,滿足:| nums[i] - nums[j] | <= t 且下標:| i - j | <= k

可以想到,維護一個大小為k的二叉搜尋樹BST,遍歷陣列中的元素,在BST上搜索有沒有符合條件的數對,若存在則直接返回true,否則將當前元素數對插入BST,並更新這個BST(若此時BST的大小已為k,需要刪掉一個值)。保證BST的大小小於或等於為k,是為了保證裡面的數下標差值一定符合條件:| i - j | <= k。實現時,可使用mulitset來實現BST

mulitset是一個有序的容器,裡面的元素都是排序好的,且允許出現重複的元素,支援插入,刪除,查詢等操作,就像一個集合一樣。multiset內部以平衡二叉樹實現。因此所有的操作的都是嚴格在O(logn)時間之內完成,效率較高。

三. 示例程式碼

// 方法一,由於vector無序,需要排列一次
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
         if(nums.size() < 2) return false;
         vector<pair<long, int>> value;
         for (int i = 0; i < nums.size(); ++i)
            value.push_back(pair<long
, int>(nums[i], i)); sort(value.begin(), value.end()); for (int i = nums.size() - 1; i >= 1; --i) { for (int j = i - 1; j >= 0; --j) { if (value[i].first - value[j].first > t) break; else if (abs(value[i].second - value[j].second) <= k) return true; else continue; } } return false; } };
// 方法二
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
    multiset<int> window; // 維護一個大小為k的視窗
    for (int i = 0; i < nums.size(); ++i) {
        if (i > k) window.erase(nums[i - k - 1]); // 保持window內只有最新k個元素,間接保證視窗內各元素下標不超過k
        auto pos = window.lower_bound(nums[i] - t); 
        if (pos != window.end() && *pos - nums[i] <= t) return true;
        window.insert(nums[i]);
    }
    return false;
}

四. 小結

練習了集合類set和mulitset的使用。相關題目有:Contains Duplicate II和Contains Duplicate I