220. Contains Duplicate III—medium
2016-07-26 23:20
603 查看
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] andnums[j] is at most t and the difference between i and j is at most k.
题目解释:并不是要求所有,只要有一组满足即可
暴力法:(超时)
下面的借鉴的一种,最差复杂度也是O(N^2),但是出现最差情况的几率很小
题目解释:并不是要求所有,只要有一组满足即可
暴力法:(超时)
class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { if (nums.size() <= 1 || k == 0) return false; vector<long int> numDiff; vector<long int> sumVec(nums.size()); sumVec[0] = 0; for (int i = 0; i < nums.size() - 1; i ++){ numDiff.push_back(nums[i+1] - nums[i]); //nums[j] - nums[i] = numDiff[i] + numDiff[i+1] + ... + numDiff[j-1] } for(int i = 0; i < nums.size(); i ++){ for (int len = 1; len <= k && i + len < nums.size(); len ++){ sumVec[len] = sumVec[len - 1] + numDiff[i+len-1]; if(abs(sumVec[len]) <= t) return true; } } return false; } };
下面的借鉴的一种,最差复杂度也是O(N^2),但是出现最差情况的几率很小
class Solution { public: static bool lessthan(pair<int, int> a, pair<int, int> b){ return a.first < b.first; } bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { vector<pair<int, int> > a; for (int i = 0; i < nums.size(); i ++){ a.push_back(make_pair(nums[i], i)); } sort(a.begin(), a.end(), lessthan); int big = 0, small = 0; for(int big = 1; big < nums.size(); big ++){ while((long)a[big].first - a[small].first > t) small ++; for(int j = small; j < big; j ++){ if (abs(a[big].second - a[j].second) <= k){ return true; } } } return false; } };
相关文章推荐
- 2016 Multi-University Training Contest 3 1011【鸽巢原理】
- 2016 Multi-University Training Contest 3
- 2016 Multi-University Training Contest 3 1002 Permutation Bo
- hdu 5754 2016 Multi-University Training Contest 3(各种博弈)
- 2016 Multi-University Training Contest 3 1001 Sqrt Bo
- POJ Problem 1363 Rails 【栈】
- Along with all the above benefits, you cannot overlook the space efficiency and performance gains in using DataFrames and Dataset APIs for two reasons.
- hdu 5753 Permutation Bo(2016 Multi-University Training Contest 3——组合)
- No.011 Container With Most Water
- 当你输入一个网址/点击一个链接,发生了什么?(以www.baidu.com为例)
- Apache 安装出现 Failed to open the Windows service manager, perhaps you forgot to log in as Adminstrator
- 2016 Multi-University Training Contest 3 Sqrt Bo
- main调用静态函数时候注意问题
- 2016 Multi-University Training Contest 3 Rower Bo
- shairo中的cache
- HDU 5319-Painter
- 算法竞赛入门经典 刽子手游戏 Rail ,Hangman judge UVa 489
- UVA 442-Matrix Chain Multiplication
- Climb Stairs
- 个人对main函数解析