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 };
  • 相关阅读:
    【第一周】进度条
    【第二周】Java实现英语文章词频统计(改进1)
    【第二周】关于java.util包下的Random类
    【第二周】结对编程(宫丽君和林莉):四则运算
    【第二周】scrum站立会议
    【第二周】燃尽图
    【第二周】Java实现英语文章词频统计
    【第一周】读《构建之法》有感
    python:带参数的装饰器,函数的有用信息
    python:数据类型dict
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4741163.html
Copyright © 2011-2022 走看看