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 };

 

posted @ 2015-08-19 03:43  amazingzoe  阅读(151)  评论(0编辑  收藏  举报