zoukankan      html  css  js  c++  java
  • Contain 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.

    Analyse:

    1. Traversal each element with the remaining elements in the array. If requirements satisfied, return true.

        Time Exceeded Limited.

     1 class Solution {
     2 public:
     3     bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
     4         for(int i = 0; i < nums.size(); i++){
     5             for(int j = i + 1; j < nums.size() && j - i <= k; j++){
     6                 if(nums[j] - nums[i] <= t && nums[j] - nums[i] >= -t) return true;
     7             }
     8         }
     9         return false;
    10     }
    11 };
    View Code
     1 class Solution {
     2 public:
     3     bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
     4         for(int i = 0; i < nums.size(); i++){
     5             for(int j = i + 1; j < nums.size(); j++){
     6                 if(nums[j] - nums[i] > t || nums[j] - nums[i] < -t) continue;
     7                 if(j - i <= k) return true;
     8             }
     9         }
    10         return false;
    11     }
    12 };
    View Code

    2. 

        Runtime: 20ms.

     1 class Solution {
     2 public:
     3     static bool cmpptr(int *a, int *b){
     4         return *a < *b; 
     5     }
     6     bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
     7         const int N = nums.size();
     8         vector<int*> numptrs(N);
     9         for(int i = 0; i < N; ++i){
    10             numptrs[i] = &nums[i];
    11         }
    12         sort(numptrs.begin(), numptrs.end(), cmpptr);
    13         for(int i = 0; i < N; i++){
    14             for(int j = i + 1; j < N; j++){
    15                 //nums[i] and nums[j] is at most t
    16                 if((*numptrs[j]) > (*numptrs[i]) + t) 
    17                     break;
    18                 //the difference between i and j is at most k
    19                 if(abs(numptrs[j] - numptrs[i]) <= k) return true;
    20             }
    21         }
    22         return false;
    23     }
    24     
    25 };
  • 相关阅读:
    Network (poj1144)
    C. Hongcow Builds A Nation
    ZYB loves Xor I(hud5269)
    D. Chloe and pleasant prizes
    Game(hdu5218)
    约瑟夫环的递推方法
    Misaki's Kiss again(hdu5175)
    Exploration(hdu5222)
    B. Arpa's weak amphitheater and Mehrdad's valuable Hoses
    C. Arpa's loud Owf and Mehrdad's evil plan
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4741163.html
Copyright © 2011-2022 走看看