• 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 };
  • 相关阅读:
    自定义sql server 聚合涵数
    EF CodeFirst学习笔记004--足够聪明
    EF CodeFirst学习笔记003--如何创建表
    EF CodeFirst学习笔记002--更新数据库表
    EF CodeFirst学习笔记001--主键约定
    SQL Server 2008中SQL增强之一:Values新用途 001
    SQLServer 学习笔记 序
    设计模式之单例模式
    如何控制数据库表中的某个字段的权限
    利用ResultFilter实现asp.net mvc3 页面静态化
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4741163.html
Copyright © 2020-2023  润新知