[Leetcode 219, Easy] Contains Duplicate II
2015-06-03 09:07
381 查看
Problem:
Given an array of integers and an integer k,
find out whether there there are two distinct indices i and j in
the array such that nums[i] = nums[j] and
the difference between i andj is
at most k.
Analysis:
Solutions:
C++:
Python:
Given an array of integers and an integer k,
find out whether there there are two distinct indices i and j in
the array such that nums[i] = nums[j] and
the difference between i andj is
at most k.
Analysis:
Solutions:
C++:
static bool CompareLess(pair<int, int> left, pair<int, int> right) { if((left.first < right.first) || (left.first == right.first && left.second < right.second)) return true; return false; } bool containsNearbyDuplicate(vector<int>& nums, int k) { if(nums.size() < 2 || k < 0) return false; vector<pair<int, int> > indexed_elements; for(int i = 0; i < nums.size(); ++i) indexed_elements.push_back(make_pair(nums[i], i)); sort(indexed_elements.begin(), indexed_elements.end(), CompareLess); for(int i = 0; i < indexed_elements.size();) { if(i == indexed_elements.size() - 1) break; if(indexed_elements[i].first == indexed_elements[i + 1].first) { vector<int> indices(1, indexed_elements[i].second); int j = i + 1; cout << indexed_elements.size() << endl; for(; j < indexed_elements.size() && indexed_elements[j].first == indexed_elements[j - 1].first; ++j) indices.push_back(indexed_elements[j].second); i = j; for(j = 0; j < indices.size() - 1; ++j) { if(indices[j + 1] - indices[j] <= k) return true; } } else ++i; } return false; }Java:
Python:
相关文章推荐
- sendMail 发邮件 tls
- 【安卓学习之路1】轻轻一点,好神奇——给activity_main.xml添加Button控件
- URAL 1152 Faise Mirrors 状压DP 简单题
- Container With Most Water
- Motion Hosts Wheelchair
- videos and multimediaIn
- 安装问题Error: dl failure on line 864
- [LeetCode] Contains Duplicate II
- hdu1848 Fibonacci again and again(SG函数博弈)
- Mac系统安装Rails
- #219 Contains Duplicate II
- [leetcode] Contains Duplicate III
- 大数据引发的联想--人工智能
- 暴力/DP Codeforces Beta Round #22 (Div. 2 Only) B. Bargaining Table
- opencv源码研究: icvGetHaarTrainingDataFromBG和icvGetHaarTrainingDataFromVec的区别
- LightOJ-1138 Trailing Zeroes (III) (二分搜索)
- UVa 514 - Rails
- Solr使用SolrJ出现Lock obtain timed out: NativeFSLock
- http://blog.csdn.net/wzzvictory/article/details/16994913
- manage_data_in_containers