【LeetCode】217 & 219 - Contains Duplicate & Contains Duplicate II
2015-08-02 15:00
429 查看
217 - Contains Duplicate
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Solution 1: sort then compare the adjacent number
Solution 2: map记录已存在的int
219 - Contains Duplicate II
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 iand j is at most k.
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Solution 1: sort then compare the adjacent number
class Solution { public: bool containsDuplicate(vector<int>& nums) { //runtime:40ms if(nums.size()<=1)return false; sort(nums.begin(),nums.end()); for(int i=1;i<nums.size();i++){ if(nums[i-1]==nums[i])return true; } return false; } };
Solution 2: map记录已存在的int
class Solution { public: bool containsDuplicate(vector<int>& nums) { //runtime:104ms if(nums.size()<=1)return false; map<int,bool> m; for(int i=0;i<nums.size();i++){ if(m[nums[i]]==true)return true; m[nums[i]]=true; } return false; } };
219 - Contains Duplicate II
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 iand j is at most k.
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { map<int,int> m; for(int i=0;i<nums.size();i++){ if(m.find(nums[i])==m.end()) m[nums[i]]=i; else{ if(i-m[nums[i]]<=k) return true; else m[nums[i]]=i; } } return false; } };
相关文章推荐
- LeetCode:Climbing Stairs(DP)
- MainWindow简介
- tftp服务器连接开发板下载内核提示:retry count exceeded; starting again
- RuntimeError: Broken toolchain: cannot link a simple C program
- ORA-02291: integrity constraint (SYSTEM.FK1170E5C5328E4352) violated 解决办法
- 机器学习(吴恩达授课)课堂笔记(1)- Intro
- mvn generate-sources failed: Invalid SDK: Platform/API level 15 not available
- 2015 Multi-University Training Contest 3 hdu 5325 Crazy Bobo
- HDU 5335 || Walk Out || 2015 Multi-University Training Contest 4 简单题
- 2015 Multi-University Training Contest 3 hdu 5317 RGCDQ
- 朴素贝叶斯分类算法(Naive Bayesian classification)
- hdu 5319 Painter
- HDU 3452 Bonsai(最小割)
- HDUOJ Train Problem I
- 如何减少浏览器repaint和reflow ?
- wait 和 sleep的区别
- 2015 Multi-University Training Contest 4(hdu 5327 - hdu 5338)
- Rails 极简入门笔记
- Aircrack-ng 简单的WEP加密破解(下)
- ZOJ_1012_Mainframe